feat(identity): verify provider tokens and attribute task actions to their actor

Two halves of one boundary: a credential resolves to an identity, and an action
records which identity acted and whose authority it used.

resource server. internal/infrastructure/oidc verifies a provider-issued bearer
token against the provider's published keys, using an OSS OIDC library: archie
compares no signature, validates no claim and rotates no key itself, holds no
client secret and issues no session, so a compromised archie cannot mint an
identity. Audience is required rather than optional -- a token minted for another
service must not authenticate here -- and discovery happens at construction, so an
unreachable provider is a startup failure rather than a request-time surprise.

identity.Authenticate is the single place a credential becomes an identity, and it
refuses in four distinguishable ways: no credential presented, a credential that
did not verify (wrong key, expired, wrong issuer, wrong audience, malformed), a
verified subject with no identity bound to it, and an identity that may not act.
The order is deliberate: verification happens before any field of the token is
used, so nothing an unverified token carries can select an identity. A suspended
identity is refused even though its credential verified, because suspension is
archie's decision and must not depend on the provider withdrawing a token.

The binding is the second bridge beside the legacy-name alias: identity_subjects
keys (issuer, subject) so the same subject string from another issuer is a
different caller, and rebinding moves a subject so two identities can never claim
one provider subject. The contract Authenticate needs is SubjectResolver, narrower
than Repository, so a consumer that only authenticates does not take the whole
identity CRUD surface -- and staterpc.Client, which asserts Repository, does not
need a new RPC to satisfy it.

attribution. taskactions now records two identities per action: the acting
identity and the authorising principal, both on the event row as new columns added
through the existing migration table. The rule that the bug turned on is enforced
by the event kind describing the actor: a person's approval is human_approved, an
agent's is agent_approved, and an action with no verified actor is task_approved,
a task-level event that credits nobody. An agent acting under a person's standing
approval records itself as the actor and that person as the principal, so
"approved by came from me" is answerable from the record rather than asserted.
Scope and actor are separated: scope decides which task a caller may touch and is
never promoted into an actor, because the dashboard's credential is a shared token
and possession of it is not evidence that a person was at the keyboard.

That last point is a deliberate fidelity trade, and the reason the transport is
not wired: the dashboard action path passes no actor yet, so dashboard approvals
are now recorded as task_approved rather than claimed as a human's. Recording
nothing false is the requirement; naming the human verifiably needs the dashboard
to authenticate a token and resolve it, which needs two new state-store RPCs
(ResolveIdentitySubject, BindIdentitySubject) -- the next piece, not a rewrite:
the verifier is a one-method interface, so introspection would be a second
implementation of it.

Verified: task check exit 0; focused runs recorded in the handoff. Opaque
authelia_at_ tokens were inspected rather than assumed and cannot be verified
against public keys; infra is configuring access_token_signed_response_alg RS256
on the archie client, with audience https://archie.catlow.cloud and issuer
https://auth.catlow.cloud.
This commit is contained in:
sam committed 2026-09-22 14:34:16 +10:00
1 parent 06800c621a
commit a7d6f71d5a
19 files changed
+1146 -88

No files matched your search

+3
View File
@@ -51,6 +51,7 @@ require (
go.yaml.in/yaml/v3 v3.0.5 // indirect
golang.org/x/crypto v0.57.0 // indirect
golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect
golang.org/x/oauth2 v0.36.0 // indirect
golang.org/x/sync v0.23.0 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.42.0 // indirect
@@ -66,8 +67,10 @@ require (
cel.dev/cel-go v0.32.0
code.gitea.io/sdk/gitea v0.25.1
github.com/BurntSushi/toml v1.6.0
github.com/coreos/go-oidc/v3 v3.21.0
github.com/go-git/go-billy/v6 v6.0.0-alpha.2
github.com/go-git/go-git/v6 v6.0.0-alpha.5
github.com/go-jose/go-jose/v4 v4.1.4
github.com/go-telegram/bot v1.27.0
github.com/google/codesearch v1.3.0-rc.1
github.com/google/go-github/v78 v78.0.0
+4 -30
View File
@@ -2,21 +2,16 @@ cel.dev/cel-go v0.32.0 h1:irvpFKr5EuGPyxeME03ERh0rii1TX+BDAnB9eL3IvNk=
cel.dev/cel-go v0.32.0/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU=
cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0=
cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
cloud.google.com/go/auth v0.23.1/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE=
code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg=
github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU=
github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps=
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM=
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
github.com/antithesishq/antithesis-sdk-go v0.8.0 h1:bVV5ZAuwaREn4klRSJusYaA+A7NXq8Qi9C/knCaQ2N4=
@@ -25,18 +20,16 @@ github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYW
github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=
github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=
github.com/bwesterb/go-ristretto v1.2.4/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0=
@@ -51,10 +44,6 @@ github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
github.com/envoyproxy/go-control-plane/envoy v1.39.0/go.mod h1:5e4ylfTZO723MEEFsCpSW4ZEBWR8mwkEyXfwJBTCZ9c=
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=
@@ -69,17 +58,15 @@ github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1 h1:gmqi2jvsreu0s8JMLylYDFq4s
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1/go.mod h1:ECf1MqJlBdYpKggBrOXjo/0EnvRZx6D++I86UYjPgAQ=
github.com/go-git/go-git/v6 v6.0.0-alpha.5 h1:sE+OlkHgYWNMVmN1s9sR7uyFgsWLtxcNWse/vBYKxRE=
github.com/go-git/go-git/v6 v6.0.0-alpha.5/go.mod h1:3IjhiZnM+uBmUrOGSeqrJpsmi4Vd0H2NZO/uK2a7d0s=
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
github.com/go-telegram/bot v1.27.0 h1:PG9yBDzM8O26oUerE9SZwWlHon4RpH8WcNslZ7CEZmE=
github.com/go-telegram/bot v1.27.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/codesearch v1.3.0-rc.1 h1:vSFGuF5wS3sjimuLzqPG+PGjWQ9VvEtPFbxdZD7YuuQ=
@@ -93,14 +80,10 @@ github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfh
github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU=
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/enterprise-certificate-proxy v0.3.21/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg=
github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=
github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
@@ -128,7 +111,6 @@ github.com/moby/moby/api v1.56.0 h1:GQzua3NA599ASSIICx0iFgiJeO9YkdDARvQsm23ZZuQ=
github.com/moby/moby/api v1.56.0/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
github.com/moby/moby/client v0.6.0 h1:AJjEB21QPbXSXjDsZorFBoDZPhMrfbpaPLgSMAW9Bgs=
github.com/moby/moby/client v0.6.0/go.mod h1:OCo00wNRyA3m4lmJ228W3JbyCN4ZNNYjpOXiJydBdcQ=
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
github.com/nats-io/nats-server/v2 v2.15.0 h1:M99yf0y05rTr46/qc/Is6ZAowI58Ryp2SjufLCUeVJc=
@@ -149,20 +131,15 @@ github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
github.com/samcharles93/ai-sdk v0.1.39 h1:gbNPYeA27MifReCruBiqMgb4fFSjCDi1Zv57a9bo0Vo=
github.com/samcharles93/ai-sdk v0.1.39/go.mod h1:u4zrQ9/Q58L5mNEut4bNQ1ks+RCKq71LN5EDz2N/0Zk=
github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY=
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
@@ -171,7 +148,6 @@ github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
@@ -199,6 +175,7 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
@@ -221,11 +198,8 @@ golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
google.golang.org/genproto/googleapis/api v0.0.0-20260918162117-cecb64721679 h1:FEp7JNE32DTAwbnI/ixagnmj7Xm1eTONofGEUXFjZ4w=
google.golang.org/genproto/googleapis/api v0.0.0-20260918162117-cecb64721679/go.mod h1:52bV8FLAQ9Qmcqaq9ECLmuEHZthk+6OPV45aKBBrsNw=
google.golang.org/genproto/googleapis/rpc v0.0.0-20260918162117-cecb64721679 h1:KmqdJU4vrNcxy/6qdg3JduZtalEXrJLspVltnR1cE+8=
@@ -9,6 +9,7 @@ import (
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/store"
@@ -24,7 +25,7 @@ type testTaskActor struct{ b *boot }
func (a testTaskActor) ApplyChatTaskAction(
ctx context.Context, identity *string, taskID int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
if err := a.b.taskActions().Apply(ctx, identity, taskID, action); err != nil {
if err := a.b.taskActions().Apply(ctx, identity, taskactions.Actor{}, taskID, action); err != nil {
return gateway.TaskActionResult{}, err
}
return gateway.TaskActionResult{
+108
View File
@@ -0,0 +1,108 @@
package identity
import (
"context"
"errors"
"fmt"
"strings"
"time"
)
// Subject is what an identity provider asserts about a caller. Issuer is part
// of the key because two providers can assert the same subject string for
// different people, and a binding keyed on the subject alone would accept one
// for the other.
type Subject struct {
Issuer string `json:"issuer"`
Subject string `json:"subject"`
}
func (s Subject) Validate() error {
if strings.TrimSpace(s.Issuer) == "" || strings.TrimSpace(s.Subject) == "" {
return fmt.Errorf("%w: issuer and subject are required", ErrInvalid)
}
return nil
}
// Credential is what a provider-issued token proved. It is the result of
// verification, never an assertion from the caller.
type Credential struct {
Subject Subject
Scopes []string
Expires time.Time
}
// Verifier checks a presented bearer token against the identity provider's
// published keys. Implementations hold no secret and mint nothing: they can
// confirm an identity the provider issued, and can never produce one.
type Verifier interface {
Verify(ctx context.Context, rawToken string) (Credential, error)
}
// SubjectResolver resolves a verified provider subject to the identity bound to
// it. It is deliberately narrower than Repository: authenticating a request
// needs to resolve a subject, not to administer identities, so a consumer that
// only authenticates does not take a dependency on the whole identity CRUD
// surface.
type SubjectResolver interface {
// ResolveSubject returns the identity a provider subject is bound to. It is
// the second binding beside the legacy-name alias: a name archie was
// configured with resolves to an identity, and a subject a provider asserts
// resolves to the same identity.
ResolveSubject(context.Context, Subject) (Identity, error)
}
var (
// ErrNoCredential means the request presented nothing to authenticate with.
ErrNoCredential = errors.New("no credential presented")
// ErrCredentialRejected means a credential was presented and did not
// verify: wrong signature, expired, wrong issuer, wrong audience, or
// malformed. It never means the credential was merely unrecognised.
ErrCredentialRejected = errors.New("credential rejected")
// ErrSubjectUnbound means a verified subject has no identity bound to it.
// The provider authenticated someone archie does not know.
ErrSubjectUnbound = errors.New("credential subject is not bound to an identity")
// ErrIdentityInactive means the identity the credential belongs to may not
// act: suspended or retired. Authentication succeeded and authorisation
// did not, which is why it is a distinct refusal from a bad credential.
ErrIdentityInactive = errors.New("identity may not act")
)
// Authenticate resolves a presented credential to the identity that may act.
//
// The order is deliberate: the credential is verified by the provider's own
// keys before anything it contains is used, so no field of an unverified token
// can select an identity. A suspended identity is refused even though its
// credential verified, because suspension is archie's decision and must not
// depend on the provider withdrawing a token.
func Authenticate(ctx context.Context, subjects SubjectResolver, verifier Verifier, rawToken string) (Identity, Credential, error) {
if strings.TrimSpace(rawToken) == "" {
return Identity{}, Credential{}, ErrNoCredential
}
if verifier == nil {
return Identity{}, Credential{}, fmt.Errorf("%w: no identity provider is configured", ErrCredentialRejected)
}
credential, err := verifier.Verify(ctx, rawToken)
if err != nil {
return Identity{}, Credential{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err)
}
if err := credential.Subject.Validate(); err != nil {
return Identity{}, Credential{}, fmt.Errorf("%w: %w", ErrCredentialRejected, err)
}
value, err := subjects.ResolveSubject(ctx, credential.Subject)
if err != nil {
if errors.Is(err, ErrNotFound) {
return Identity{}, Credential{}, fmt.Errorf("%w: %s", ErrSubjectUnbound, credential.Subject.Subject)
}
return Identity{}, Credential{}, err
}
if !value.CanAct() {
return Identity{}, Credential{}, fmt.Errorf("%w: %s is %s", ErrIdentityInactive, value.ID, value.Lifecycle)
}
return value, credential, nil
}
// CanAct reports whether an identity may perform actions. Only an active
// identity may: a suspended identity is suspended from acting, and a retired
// one is kept for attribution, not for use.
func (i Identity) CanAct() bool { return i.Lifecycle == LifecycleActive }
+161
View File
@@ -0,0 +1,161 @@
package identity
import (
"context"
"errors"
"testing"
)
type stubVerifier struct {
credential Credential
err error
}
func (s stubVerifier) Verify(context.Context, string) (Credential, error) {
return s.credential, s.err
}
type stubSubjects struct {
value Identity
err error
}
func (s stubSubjects) ResolveSubject(context.Context, Subject) (Identity, error) {
return s.value, s.err
}
func testIdentity(kind Kind, lifecycle Lifecycle) Identity {
return Identity{ID: "10000000-0000-5000-8000-000000000001", Kind: kind, DisplayName: "tester", Lifecycle: lifecycle, Version: 1}
}
func TestAuthenticateRefusesEveryUnprovenCaller(t *testing.T) {
verified := Credential{Subject: Subject{Issuer: "https://idp.example", Subject: "sam"}}
rejected := errors.New("signature verification failed")
tests := []struct {
name string
rawToken string
verifier Verifier
subjects SubjectResolver
want error
}{
{
name: "no credential presented",
rawToken: "",
verifier: stubVerifier{credential: verified},
subjects: stubSubjects{value: testIdentity(KindUser, LifecycleActive)},
want: ErrNoCredential,
},
{
name: "whitespace is not a credential",
rawToken: " ",
verifier: stubVerifier{credential: verified},
subjects: stubSubjects{value: testIdentity(KindUser, LifecycleActive)},
want: ErrNoCredential,
},
{
name: "no provider is configured, so nothing can be verified",
rawToken: "token",
verifier: nil,
subjects: stubSubjects{value: testIdentity(KindUser, LifecycleActive)},
want: ErrCredentialRejected,
},
{
name: "token signed by the wrong key is rejected",
rawToken: "token",
verifier: stubVerifier{err: rejected},
subjects: stubSubjects{value: testIdentity(KindUser, LifecycleActive)},
want: ErrCredentialRejected,
},
{
name: "verified credential with no identity bound to its subject",
rawToken: "token",
verifier: stubVerifier{credential: verified},
subjects: stubSubjects{err: ErrNotFound},
want: ErrSubjectUnbound,
},
{
name: "verified credential for a suspended identity",
rawToken: "token",
verifier: stubVerifier{credential: verified},
subjects: stubSubjects{value: testIdentity(KindBot, LifecycleSuspended)},
want: ErrIdentityInactive,
},
{
name: "verified credential for a retired identity",
rawToken: "token",
verifier: stubVerifier{credential: verified},
subjects: stubSubjects{value: testIdentity(KindBot, LifecycleRetired)},
want: ErrIdentityInactive,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got, _, err := Authenticate(context.Background(), tc.subjects, tc.verifier, tc.rawToken)
if !errors.Is(err, tc.want) {
t.Fatalf("Authenticate() error = %v, want %v", err, tc.want)
}
if got != (Identity{}) {
t.Fatalf("Authenticate() returned identity %+v on a refusal", got)
}
})
}
}
func TestAuthenticateResolvesAnActiveIdentity(t *testing.T) {
want := testIdentity(KindBot, LifecycleActive)
verified := Credential{
Subject: Subject{Issuer: "https://idp.example", Subject: "archie-agent"},
Scopes: []string{"tasks:write"},
}
got, credential, err := Authenticate(context.Background(), stubSubjects{value: want}, stubVerifier{credential: verified}, "token")
if err != nil {
t.Fatalf("Authenticate() error = %v", err)
}
if got != want {
t.Fatalf("Authenticate() identity = %+v, want %+v", got, want)
}
if credential.Subject != verified.Subject {
t.Fatalf("Authenticate() credential subject = %+v, want %+v", credential.Subject, verified.Subject)
}
}
func TestCanActOnlyForAnActiveIdentity(t *testing.T) {
tests := []struct {
lifecycle Lifecycle
want bool
}{
{LifecycleActive, true},
{LifecycleSuspended, false},
{LifecycleRetired, false},
}
for _, tc := range tests {
value := testIdentity(KindUser, tc.lifecycle)
if got := value.CanAct(); got != tc.want {
t.Errorf("Identity{%s}.CanAct() = %t, want %t", tc.lifecycle, got, tc.want)
}
}
}
func TestSubjectRequiresBothHalves(t *testing.T) {
tests := []struct {
name string
subject Subject
wantErr bool
}{
{"complete", Subject{Issuer: "https://idp.example", Subject: "sam"}, false},
{"no issuer", Subject{Subject: "sam"}, true},
{"no subject", Subject{Issuer: "https://idp.example"}, true},
{"blank", Subject{Issuer: " ", Subject: " "}, true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
err := tc.subject.Validate()
if tc.wantErr != (err != nil) {
t.Fatalf("Subject.Validate() error = %v, wantErr %t", err, tc.wantErr)
}
})
}
}
+126 -34
View File
@@ -5,7 +5,9 @@ import (
"context"
"errors"
"fmt"
"strings"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -29,6 +31,84 @@ type Task struct {
Attempt int
}
// Actor is the identity that performed an action, and the principal whose
// authority permitted it.
//
// The two are separate fields because an agent acting under a person's standing
// approval is not the same fact as a person acting: a record that collapsed
// them would answer "who approved this" with the wrong identity. An empty
// Principal means UNATTRIBUTED -- no authority was recorded, which is a
// different fact from the actor authorising itself.
type Actor struct {
Identity identity.IdentityID
Kind identity.Kind
Principal identity.IdentityID
}
// ActorFor builds an actor from the identity a credential resolved to. The kind
// travels with the actor so an event can record that an agent acted without a
// consumer having to resolve the identity to find out.
func ActorFor(value identity.Identity) Actor {
return Actor{Identity: value.ID, Kind: value.Kind}
}
// AuthorisedBy records where an action's authority came from.
func (a Actor) AuthorisedBy(principal identity.IdentityID) Actor {
a.Principal = principal
return a
}
// Human reports whether a person performed the action. Only a human's action is
// recorded as a human's: the event kind describes the actor.
func (a Actor) Human() bool { return a.Kind == identity.KindUser }
// Attributed reports whether the action is attributed to an identity. An action
// with no identity is still recorded -- refusing it would hide the action from
// the timeline -- but its record claims nothing about who performed it, and its
// kind says so.
func (a Actor) Attributed() bool { return strings.TrimSpace(string(a.Identity)) != "" }
// describe renders the attribution for a human reading a task timeline.
func (a Actor) describe(verb string) string {
if !a.Attributed() {
return verb + " with no recorded actor"
}
text := verb + " by " + string(a.Identity)
if a.Kind != "" {
text += " (" + string(a.Kind) + ")"
}
if a.Principal != "" {
return text + ", authorised by " + string(a.Principal)
}
return text + ", no authorising principal"
}
// approvedKind and rejectedKind name what happened and who did it. There is no
// single kind for an approval: an agent's approval recorded as a human's is the
// falsehood this trio exists to prevent, and an action with no verified actor
// is recorded as a task-level event rather than credited to anyone.
func approvedKind(actor Actor) string {
switch {
case actor.Human():
return events.KindHumanApproved
case actor.Attributed():
return events.KindAgentApproved
default:
return events.KindTaskApproved
}
}
func rejectedKind(actor Actor) string {
switch {
case actor.Human():
return events.KindHumanRejected
case actor.Attributed():
return events.KindAgentRejected
default:
return events.KindTaskRejected
}
}
type Store interface {
TaskByID(context.Context, int64) (*Task, error)
Transition(context.Context, int64, string, string, string) error
@@ -49,9 +129,13 @@ type Service struct {
Warn func(string, ...any)
}
// Apply scopes chat requests to an identity. A nil identity denotes an
// authenticated dashboard operator, who may act across identities.
func (s Service) Apply(ctx context.Context, identity *string, id int64, action taskstate.Action) error {
// Apply scopes chat requests to an identity. A nil scope denotes a caller
// authenticated across identities, which is the dashboard's own credential;
// scope limits which task a chat identity may act on, and never says who acted.
//
// The actor is not derived from scope: scope is which tasks a caller may touch,
// actor is who touched one, and the two are only equal by coincidence.
func (s Service) Apply(ctx context.Context, scope *string, actor Actor, id int64, action taskstate.Action) error {
task, err := s.Store.TaskByID(ctx, id)
if err != nil {
return err
@@ -59,18 +143,18 @@ func (s Service) Apply(ctx context.Context, identity *string, id int64, action t
if task == nil {
return fmt.Errorf("task %d: %w", id, ErrNotFound)
}
if identity != nil && task.Identity != *identity {
return fmt.Errorf("task %d belongs to %q, not %q", id, task.Identity, *identity)
if scope != nil && task.Identity != *scope {
return fmt.Errorf("task %d belongs to %q, not %q", id, task.Identity, *scope)
}
if err := taskstate.CheckAction(task.Status, action); err != nil {
return fmt.Errorf("%w: %w", ErrConflict, err)
}
mutation, err := s.apply(ctx, task, identity, action)
mutation, err := s.apply(ctx, task, actor, action)
if err != nil {
return err
}
if mutation.verb != "" && task.ForgeBacked {
s.closeRejectedIssue(ctx, task, identity, mutation.verb)
s.closeRejectedIssue(ctx, task, actor, mutation.verb)
}
s.emit(ctx, mutation.event)
return nil
@@ -85,37 +169,48 @@ type outcome struct {
// record alongside it. Errors from the store are returned unwrapped: the
// caller maps them to a response, and the rules-level errors (ErrConflict)
// were already checked above.
func (s Service) apply(ctx context.Context, task *Task, identity *string, action taskstate.Action) (outcome, error) {
source := "the dashboard"
if identity != nil {
source = "chat"
}
o := outcome{event: events.Event{TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Attempt: task.Attempt}}
func (s Service) apply(ctx context.Context, task *Task, actor Actor, action taskstate.Action) (outcome, error) {
o := outcome{event: s.attributed(task, actor)}
switch action {
case taskstate.ActionApprove:
err := s.Store.Requeue(ctx, task.ID, "waiting_human", "implement")
o.event.Kind, o.event.Detail = events.KindHumanApproved, "approved via "+source
o.event.Kind, o.event.Detail = approvedKind(actor), actor.describe("approved")
return o, err
case taskstate.ActionRetry:
return s.applyRetry(ctx, task, source, o)
return s.applyRetry(ctx, task, actor, o)
case taskstate.ActionStop:
return s.applyStop(ctx, task, source, o)
return s.applyStop(ctx, task, actor, o)
case taskstate.ActionReject:
o.event.Kind, o.event.Detail, o.verb = events.KindHumanRejected, "rejected via "+source, "rejected"
o.event.Kind, o.event.Detail, o.verb = rejectedKind(actor), actor.describe("rejected"), "rejected"
if task.Status == "running" && s.CancelTask != nil {
s.CancelTask(task.ID)
}
return o, s.Store.Transition(ctx, task.ID, task.Status, "closed_wont_do", "declined from "+source)
return o, s.Store.Transition(ctx, task.ID, task.Status, "closed_wont_do", actor.describe("declined"))
case taskstate.ActionCancel, taskstate.ActionAbandon:
return s.applyCancelOrAbandon(ctx, task, action, source, o)
return s.applyCancelOrAbandon(ctx, task, action, actor, o)
case taskstate.ActionArchive:
return s.applyArchive(ctx, task, source, o)
return s.applyArchive(ctx, task, actor, o)
default:
return o, fmt.Errorf("unsupported task action %q", action)
}
}
func (s Service) applyRetry(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
// attributed builds the event skeleton every action carries: the task, the run
// and both identities. Every event this service records passes through here, so
// no action can be recorded without its attribution.
func (s Service) attributed(task *Task, actor Actor) events.Event {
return events.Event{
TaskID: task.ID,
Repo: task.Owner + "/" + task.Repo,
Issue: task.IssueNumber,
Attempt: task.Attempt,
ActorID: string(actor.Identity),
ActorKind: string(actor.Kind),
PrincipalID: string(actor.Principal),
}
}
func (s Service) applyRetry(ctx context.Context, task *Task, actor Actor, o outcome) (outcome, error) {
limit := 0
if s.MaxRetries != nil {
limit = s.MaxRetries(task)
@@ -131,33 +226,33 @@ func (s Service) applyRetry(ctx context.Context, task *Task, source string, o ou
return o, fmt.Errorf("%w: %s", ErrConflict, reason)
}
err := s.Store.RetryTask(ctx, task.ID, "parked", "")
o.event.Kind, o.event.Detail = events.KindTaskRetried, "retried via "+source
o.event.Kind, o.event.Detail = events.KindTaskRetried, actor.describe("retried")
o.event.Data = map[string]any{"retry_count": task.RetryCount + 1, "previous_stage": task.Stage, "previous_reason": task.ParkReason}
return o, err
}
func (s Service) applyStop(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
func (s Service) applyStop(ctx context.Context, task *Task, actor Actor, o outcome) (outcome, error) {
if s.CancelTask == nil {
return o, ErrUnavailable
}
o.event.Kind, o.event.Detail = events.KindTaskStopped, "stopped via "+source+"; recoverable work remains parked"
o.event.Kind, o.event.Detail = events.KindTaskStopped, actor.describe("stopped")+"; recoverable work remains parked"
if !s.CancelTask(task.ID) {
o.event.Detail = "no active execution was found; recoverable work was parked via " + source
o.event.Detail = "no active execution was found; recoverable work was parked, " + actor.describe("stopped")
}
return o, s.Store.Transition(ctx, task.ID, "running", "parked", o.event.Detail)
}
func (s Service) applyCancelOrAbandon(ctx context.Context, task *Task, action taskstate.Action, source string, o outcome) (outcome, error) {
func (s Service) applyCancelOrAbandon(ctx context.Context, task *Task, action taskstate.Action, actor Actor, o outcome) (outcome, error) {
from, kind, verb := "queued", events.KindTaskCancelled, "cancelled"
if action == taskstate.ActionAbandon {
from, kind, verb = "parked", events.KindTaskAbandoned, "abandoned"
}
o.event.Kind, o.event.Detail, o.verb = kind, verb+" via "+source, verb
o.event.Kind, o.event.Detail, o.verb = kind, actor.describe(verb), verb
return o, s.Store.Transition(ctx, task.ID, from, "closed_wont_do", o.event.Detail)
}
func (s Service) applyArchive(ctx context.Context, task *Task, source string, o outcome) (outcome, error) {
o.event.Kind, o.event.Detail = events.KindTaskArchiveRequested, "archive requested via "+source
func (s Service) applyArchive(ctx context.Context, task *Task, actor Actor, o outcome) (outcome, error) {
o.event.Kind, o.event.Detail = events.KindTaskArchiveRequested, actor.describe("archive requested")
id, err := s.Store.ArchiveTask(ctx, task.ID, task.Status, o.event)
if err != nil {
return o, err
@@ -171,15 +266,12 @@ func (s Service) applyArchive(ctx context.Context, task *Task, source string, o
return o, nil
}
func (s Service) closeRejectedIssue(ctx context.Context, task *Task, identity *string, verb string) {
func (s Service) closeRejectedIssue(ctx context.Context, task *Task, actor Actor, verb string) {
if s.CloseIssue == nil {
s.warn("task rejected but no forge is wired; the issue stays open and will be re-polled", "task", task.ID)
return
}
comment := fmt.Sprintf("Closing: this task was %s from the archie %s. Reopen the issue to have archie pick it up again.", verb, "dashboard")
if identity != nil {
comment = fmt.Sprintf("Closing: this task was %s from archie chat. Reopen the issue to have archie pick it up again.", verb)
}
comment := fmt.Sprintf("Closing: this task was %s in archie (%s). Reopen the issue to have archie pick it up again.", verb, actor.describe("actioned"))
if err := s.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
s.warn("closing rejected issue failed; it stays open and will be re-polled", "task", task.ID, "err", err)
}
+211
View File
@@ -0,0 +1,211 @@
package taskactions
import (
"context"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/taskstate"
)
type fakeStore struct {
task *Task
events []events.Event
}
func (f *fakeStore) TaskByID(context.Context, int64) (*Task, error) { return f.task, nil }
func (f *fakeStore) Transition(context.Context, int64, string, string, string) error {
return nil
}
func (f *fakeStore) Requeue(context.Context, int64, string, string) error { return nil }
func (f *fakeStore) RetryTask(context.Context, int64, string, string) error {
return nil
}
func (f *fakeStore) ArchiveTask(_ context.Context, _ int64, _ string, e events.Event) (int64, error) {
f.events = append(f.events, e)
return int64(len(f.events)), nil
}
func (f *fakeStore) InsertEvent(_ context.Context, e events.Event) (int64, error) {
f.events = append(f.events, e)
return int64(len(f.events)), nil
}
func (f *fakeStore) last() events.Event {
if len(f.events) == 0 {
return events.Event{}
}
return f.events[len(f.events)-1]
}
const (
humanID = identity.IdentityID("20000000-0000-5000-8000-000000000001")
agentID = identity.IdentityID("20000000-0000-5000-8000-000000000002")
)
func humanActor() Actor {
return ActorFor(identity.Identity{ID: humanID, Kind: identity.KindUser, Lifecycle: identity.LifecycleActive})
}
func agentActor() Actor {
return ActorFor(identity.Identity{ID: agentID, Kind: identity.KindBot, Lifecycle: identity.LifecycleActive})
}
// TestEventKindDescribesTheActor is the rule that the bug turned on: an agent's
// approval was written down as a human's. The kind names the actor, so an
// agent's action can never be read as a person's, and an action with no verified
// actor is recorded as a task-level event that credits nobody.
func TestEventKindDescribesTheActor(t *testing.T) {
tests := []struct {
name string
action taskstate.Action
actor Actor
wantKind string
}{
{"a person approves", taskstate.ActionApprove, humanActor(), events.KindHumanApproved},
{"an agent approves", taskstate.ActionApprove, agentActor(), events.KindAgentApproved},
{"a person rejects", taskstate.ActionReject, humanActor(), events.KindHumanRejected},
{"an agent rejects", taskstate.ActionReject, agentActor(), events.KindAgentRejected},
{"an unattributed approval", taskstate.ActionApprove, Actor{}, events.KindTaskApproved},
{"an unattributed rejection", taskstate.ActionReject, Actor{}, events.KindTaskRejected},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, tc.actor, 7, tc.action); err != nil {
t.Fatalf("Apply() error = %v", err)
}
got := store.last()
if got.Kind != tc.wantKind {
t.Fatalf("event kind = %q, want %q", got.Kind, tc.wantKind)
}
if tc.actor.Human() && got.Kind == events.KindAgentApproved {
t.Fatal("a person's action was recorded as an agent's")
}
if tc.actor.Attributed() && !tc.actor.Human() && got.Kind == events.KindHumanApproved {
t.Fatal("an agent's action was recorded as a human approval")
}
})
}
}
// TestActorAndPrincipalAreRecordedSeparately is the two-attribution requirement:
// an agent acting under a person's standing authority records both, so "approved
// by came from me" is answerable from the record.
func TestActorAndPrincipalAreRecordedSeparately(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human"}}
service := Service{Store: store}
actor := agentActor().AuthorisedBy(humanID)
if err := service.Apply(context.Background(), nil, actor, 7, taskstate.ActionApprove); err != nil {
t.Fatalf("Apply() error = %v", err)
}
got := store.last()
if got.ActorID != string(agentID) {
t.Fatalf("actor = %q, want %q", got.ActorID, agentID)
}
if got.ActorKind != string(identity.KindBot) {
t.Fatalf("actor kind = %q, want %q", got.ActorKind, identity.KindBot)
}
if got.PrincipalID != string(humanID) {
t.Fatalf("principal = %q, want %q", got.PrincipalID, humanID)
}
if got.Kind != events.KindAgentApproved {
t.Fatalf("event kind = %q, want %q", got.Kind, events.KindAgentApproved)
}
}
// TestUnattributedActionClaimsNoApprover: with no verified actor the record must
// not credit the actor's own authority, and must not name a human.
func TestUnattributedActionClaimsNoApprover(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), nil, Actor{}, 7, taskstate.ActionApprove); err != nil {
t.Fatalf("Apply() error = %v", err)
}
got := store.last()
if got.ActorID != "" || got.ActorKind != "" || got.PrincipalID != "" {
t.Fatalf("unattributed action recorded an actor: %+v", got)
}
if got.Kind == events.KindHumanApproved || got.Kind == events.KindAgentApproved {
t.Fatalf("unattributed action claimed an actor through its kind: %q", got.Kind)
}
}
// TestEveryActionCarriesItsAttribution: no action path may record an event that
// skipped the attribution, including the ones that also close a forge issue.
func TestEveryActionCarriesItsAttribution(t *testing.T) {
actions := []struct {
action taskstate.Action
status string
}{
{taskstate.ActionApprove, "waiting_human"},
{taskstate.ActionReject, "waiting_human"},
{taskstate.ActionRetry, "parked"},
{taskstate.ActionStop, "running"},
{taskstate.ActionCancel, "queued"},
{taskstate.ActionAbandon, "parked"},
}
for _, tc := range actions {
t.Run(string(tc.action), func(t *testing.T) {
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: tc.status}}
service := Service{
Store: store,
CancelTask: func(int64) bool { return true },
}
if err := service.Apply(context.Background(), nil, agentActor(), 7, tc.action); err != nil {
t.Fatalf("Apply(%s) error = %v", tc.action, err)
}
got := store.last()
if got.ActorID != string(agentID) || got.ActorKind != string(identity.KindBot) {
t.Fatalf("%s recorded without its actor: %+v", tc.action, got)
}
})
}
}
// TestScopeStillLimitsATaskButIsNotTheActor: scope answers which task a caller
// may touch. It is not an actor, and passing one must not attribute the action
// to it.
func TestScopeStillLimitsATaskButIsNotTheActor(t *testing.T) {
other := "sam"
store := &fakeStore{task: &Task{ID: 7, Owner: "acme", Repo: "widgets", Status: "waiting_human", Identity: "archie"}}
service := Service{Store: store}
if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove); err == nil {
t.Fatal("Apply() allowed an identity to act on another identity's task")
}
if len(store.events) != 0 {
t.Fatalf("a refused action recorded %d events", len(store.events))
}
if err := service.Apply(context.Background(), &other, agentActor(), 7, taskstate.ActionApprove); err == nil {
t.Fatal("Apply() allowed a scoped caller to act on a foreign task")
}
}
func TestActorForCarriesTheKindAndLeavesTheActionUnattributedWithoutAPrincipal(t *testing.T) {
actor := agentActor()
if actor.Principal != "" {
t.Fatalf("ActorFor() set a principal: %q", actor.Principal)
}
if !actor.Attributed() {
t.Fatal("ActorFor() produced an unattributed actor for a real identity")
}
if (Actor{}).Attributed() {
t.Fatal("the zero Actor reported itself as attributed")
}
if (Actor{}).Human() {
t.Fatal("the zero Actor reported itself as a human")
}
}
+32 -3
View File
@@ -39,6 +39,20 @@ const (
// seeing, because it explains why a task changed course.
KindHumanApproved = "human_approved"
KindHumanRejected = "human_rejected"
// KindAgentApproved and KindAgentRejected record that an agent performed
// the action. They exist because the event kind describes the ACTOR: an
// agent approving under a person's standing authority is not a human
// approval, and recording it as one asserts something false. The authority
// it acted under is PrincipalID, which is a separate fact.
KindAgentApproved = "agent_approved"
KindAgentRejected = "agent_rejected"
// KindTaskApproved and KindTaskRejected record an approval or rejection that
// archie cannot attribute to anyone: the request carried no identity archie
// could verify. They are task-level events that claim nothing about the
// actor, which is the honest record -- a human's approval and an agent's are
// recorded as human_* and agent_* respectively.
KindTaskApproved = "task_approved"
KindTaskRejected = "task_rejected"
// KindTaskRetried records what the retry was escaping from. RetryTask
// clears stage and park_reason in the same statement that increments the
// count, so this event is the only place that context survives.
@@ -129,9 +143,24 @@ type Event struct {
// as a first run. The tag is deliberately not omitempty so that
// unattributed and absent stay distinguishable on the wire and in the
// array the dashboard renders.
Attempt int `json:"attempt"`
Detail string `json:"detail,omitempty"`
Data map[string]any `json:"data,omitempty"`
Attempt int `json:"attempt"`
// ActorID is the identity that performed the action this event records,
// derived from the credential the request presented. Empty means the event
// has no actor: the producers that are task-agnostic or pre-date this field
// make no claim about who acted, and a reader must report that rather than
// assume a human did.
ActorID string `json:"actor_id,omitempty"`
// ActorKind is the acting identity's kind, kept beside ActorID so a reader
// can tell an agent's action from a person's without resolving the identity
// -- and so an agent's action can never be displayed as a human's.
ActorKind string `json:"actor_kind,omitempty"`
// PrincipalID is the identity whose authority the action used, which is not
// the acting identity when an agent acts under a person's standing approval
// ("approved by came from me"). Empty means UNATTRIBUTED: no authority was
// recorded, which is a different fact from the actor authorising itself.
PrincipalID string `json:"principal_id,omitempty"`
Detail string `json:"detail,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
// Sub is one subscriber: a bounded channel plus a drop counter.
+72
View File
@@ -0,0 +1,72 @@
// Package oidc verifies identity-provider tokens. It is a resource server: it
// validates a token the provider issued and never issues one, holds no client
// secret, and mints no session.
package oidc
import (
"context"
"fmt"
"strings"
gooidc "github.com/coreos/go-oidc/v3/oidc"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
// Config identifies the provider and the audience archie accepts tokens for.
// Audience is required rather than optional: without it a token the provider
// minted for a different service would authenticate here, which is the
// confused-deputy failure this boundary exists to prevent.
type Config struct {
Issuer string
Audience string
}
// Verifier validates tokens against the provider's published signing keys.
type Verifier struct {
verifier *gooidc.IDTokenVerifier
}
// New discovers the provider and builds a verifier from its published keys.
// Discovery happens once, at construction: an unreachable provider is a
// startup failure the operator sees, not a request-time surprise.
func New(ctx context.Context, cfg Config) (*Verifier, error) {
issuer := strings.TrimSpace(cfg.Issuer)
audience := strings.TrimSpace(cfg.Audience)
if issuer == "" {
return nil, fmt.Errorf("oidc: issuer is required")
}
if audience == "" {
return nil, fmt.Errorf("oidc: audience is required")
}
provider, err := gooidc.NewProvider(ctx, issuer)
if err != nil {
return nil, fmt.Errorf("oidc: discover %q: %w", issuer, err)
}
return &Verifier{verifier: provider.Verifier(&gooidc.Config{ClientID: audience})}, nil
}
// Verify checks the token's signature, issuer, audience and expiry against the
// provider's keys, and returns what it proved. Every check is the library's:
// signature comparison, claim validation and key rotation are not archie's code.
func (v *Verifier) Verify(ctx context.Context, rawToken string) (identity.Credential, error) {
if v == nil || v.verifier == nil {
return identity.Credential{}, fmt.Errorf("oidc: no verifier is configured")
}
token, err := v.verifier.Verify(ctx, strings.TrimSpace(rawToken))
if err != nil {
return identity.Credential{}, fmt.Errorf("oidc: verify: %w", err)
}
var claims struct {
Scope string `json:"scope"`
}
// Claims are read after verification and are advisory: the identity comes
// from the verified subject and issuer, never from a claim a caller could
// have written into an unverified token.
_ = token.Claims(&claims)
return identity.Credential{
Subject: identity.Subject{Issuer: token.Issuer, Subject: token.Subject},
Scopes: strings.Fields(claims.Scope),
Expires: token.Expiry,
}, nil
}
+174
View File
@@ -0,0 +1,174 @@
package oidc
import (
"context"
"crypto/rand"
"crypto/rsa"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/go-jose/go-jose/v4"
"github.com/go-jose/go-jose/v4/jwt"
)
const testAudience = "archie-dashboard"
// provider is a minimal identity provider: a discovery document and a JWKS.
// It signs with a real RSA key so every refusal below is the library's own
// signature and claim checking, not a stub's behaviour.
type provider struct {
server *httptest.Server
key *rsa.PrivateKey
keyID string
// other is a second, unrelated key used to sign a token the provider
// never published, which is what a forged or foreign token looks like.
other *rsa.PrivateKey
}
func newProvider(t *testing.T) *provider {
t.Helper()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate key: %v", err)
}
other, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate second key: %v", err)
}
p := &provider{key: key, other: other, keyID: "test-key"}
mux := http.NewServeMux()
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{
"issuer": p.server.URL,
"jwks_uri": p.server.URL + "/keys",
"authorization_endpoint": p.server.URL + "/authorize",
"token_endpoint": p.server.URL + "/token",
"response_types_supported": []string{"code"},
"subject_types_supported": []string{"public"},
"id_token_signing_alg_values_supported": []string{"RS256"},
})
})
mux.HandleFunc("/keys", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(jose.JSONWebKeySet{Keys: []jose.JSONWebKey{{
Key: key.Public(), KeyID: p.keyID, Algorithm: "RS256", Use: "sig",
}}})
})
p.server = httptest.NewServer(mux)
t.Cleanup(p.server.Close)
return p
}
// token signs a token with the given key for the given claims.
func (p *provider) token(t *testing.T, signer *rsa.PrivateKey, mutate func(*jwt.Claims)) string {
t.Helper()
claims := jwt.Claims{
Issuer: p.server.URL,
Subject: "sam",
Audience: jwt.Audience{testAudience},
Expiry: jwt.NewNumericDate(time.Now().Add(time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now().Add(-time.Minute)),
}
if mutate != nil {
mutate(&claims)
}
sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: signer},
(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", p.keyID))
if err != nil {
t.Fatalf("new signer: %v", err)
}
raw, err := jwt.Signed(sig).Claims(claims).Serialize()
if err != nil {
t.Fatalf("serialize token: %v", err)
}
return raw
}
func (p *provider) verifier(t *testing.T) *Verifier {
t.Helper()
v, err := New(context.Background(), Config{Issuer: p.server.URL, Audience: testAudience})
if err != nil {
t.Fatalf("New() error = %v", err)
}
return v
}
func TestVerifyAcceptsAProviderIssuedToken(t *testing.T) {
p := newProvider(t)
credential, err := p.verifier(t).Verify(context.Background(), p.token(t, p.key, nil))
if err != nil {
t.Fatalf("Verify() error = %v", err)
}
if credential.Subject.Subject != "sam" {
t.Fatalf("subject = %q, want %q", credential.Subject.Subject, "sam")
}
if credential.Subject.Issuer != p.server.URL {
t.Fatalf("issuer = %q, want %q", credential.Subject.Issuer, p.server.URL)
}
}
func TestVerifyRefusesEveryUnacceptableToken(t *testing.T) {
p := newProvider(t)
verifier := p.verifier(t)
tests := []struct {
name string
token string
}{
{
name: "no token",
token: "",
},
{
name: "expired",
token: p.token(t, p.key, func(c *jwt.Claims) { c.Expiry = jwt.NewNumericDate(time.Now().Add(-time.Hour)) }),
},
{
name: "signed by a key the provider never published",
token: p.token(t, p.other, nil),
},
{
name: "issued for another audience",
token: p.token(t, p.key, func(c *jwt.Claims) { c.Audience = jwt.Audience{"another-service"} }),
},
{
name: "issued by another provider",
token: p.token(t, p.key, func(c *jwt.Claims) { c.Issuer = "https://someone-else.example" }),
},
{
name: "not a token at all",
token: "not-a-jwt",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if _, err := verifier.Verify(context.Background(), tc.token); err == nil {
t.Fatal("Verify() accepted a token it must refuse")
}
})
}
}
func TestNewRefusesAnIncompleteConfiguration(t *testing.T) {
p := newProvider(t)
tests := []struct {
name string
cfg Config
}{
{"no issuer", Config{Audience: testAudience}},
{"no audience", Config{Issuer: p.server.URL}},
{"unreachable issuer", Config{Issuer: "http://127.0.0.1:1", Audience: testAudience}},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if _, err := New(context.Background(), tc.cfg); err == nil {
t.Fatal("New() accepted a configuration it must refuse")
}
})
}
}
+8 -4
View File
@@ -22,9 +22,13 @@ import (
// execution; the standalone Gateway never mutates the task store directly.
const actionSubject = "archie.gateway.task-action"
// Identity is a pointer because its absence is meaningful: nil is an
// authenticated dashboard operator acting across identities, which the
// daemon's service distinguishes from any named identity, empty included.
// Identity is a pointer because its absence is meaningful: nil is a
// authenticated dashboard operator acting across identities, which the daemon's
// service distinguishes from any named identity, empty included. It is a SCOPE
// -- which tasks the caller may touch -- and never an actor. Who acted is not on
// this request yet, so the daemon records these actions unattributed rather than
// crediting them to a human: the dashboard's own credential is a shared token,
// which is not evidence that a person was at the keyboard.
type actionRequest struct {
Identity *string `json:"identity"`
TaskID int64 `json:"task_id"`
@@ -96,7 +100,7 @@ func Register(nc *nats.Conn, service taskactions.Service, log *slog.Logger) (fun
natsrpc.Respond(msg, log, "taskactions", actionResponse{Envelope: natsrpc.NewEnvelope(err)})
return
}
err := service.Apply(context.Background(), req.Identity, req.TaskID, req.Action)
err := service.Apply(context.Background(), req.Identity, taskactions.Actor{}, req.TaskID, req.Action)
natsrpc.Respond(msg, log, "taskactions", actionResponse{
Envelope: natsrpc.NewEnvelope(err),
Kind: actionErrorKind(err),
@@ -113,7 +113,7 @@ func TestActionErrorKeepsItsSentinelAcrossNATS(t *testing.T) {
t.Fatalf("error %v (%T) is not %v", err, err, tc.want)
}
// The wording the operator reads survives too, not just the class.
direct := service.Apply(t.Context(), nil, 7, tc.action)
direct := service.Apply(t.Context(), nil, domain.Actor{}, 7, tc.action)
if direct == nil || err.Error() != direct.Error() {
t.Fatalf("remote message = %q, want the daemon's own %v", err.Error(), direct)
}
@@ -122,17 +122,17 @@ func TestActionErrorKeepsItsSentinelAcrossNATS(t *testing.T) {
}
// TestActionScopeCrossesNATS pins the operator scope over the same hop: a nil
// identity is an authenticated dashboard operator, and JSON has to carry that
// absence rather than an empty name. The service records which one acted, so
// the timeline is the observable.
// identity is a caller authenticated across identities, and JSON has to carry
// that absence rather than an empty name. The scope decides which task may be
// touched and nothing else -- it is not an actor, so it must not change what the
// timeline says about who acted.
func TestActionScopeCrossesNATS(t *testing.T) {
for _, tc := range []struct {
name string
identity *string
want string
}{
{name: "operator", want: "abandoned via the dashboard"},
{name: "chat identity", identity: new("scout"), want: "abandoned via chat"},
{name: "operator scope"},
{name: "chat identity scope", identity: new("scout")},
} {
t.Run(tc.name, func(t *testing.T) {
srv := startEmbedded(t)
@@ -159,8 +159,17 @@ func TestActionScopeCrossesNATS(t *testing.T) {
if result.TaskID != 7 {
t.Fatalf("result = %+v, want task 7", result)
}
if published.Detail != tc.want {
t.Fatalf("event detail = %q, want %q", published.Detail, tc.want)
// No actor crosses this hop yet, so the action is recorded with no
// actor at all -- and the scope must not be promoted into one.
if published.ActorID != "" || published.PrincipalID != "" {
t.Fatalf("scope was recorded as an actor: %+v", published)
}
if published.Kind != events.KindTaskAbandoned {
t.Fatalf("event kind = %q, want %q", published.Kind, events.KindTaskAbandoned)
}
const want = "abandoned with no recorded actor"
if published.Detail != want {
t.Fatalf("event detail = %q, want %q", published.Detail, want)
}
})
}
+10 -5
View File
@@ -23,6 +23,9 @@ CREATE TABLE IF NOT EXISTS events (
workflow TEXT NOT NULL DEFAULT '',
stage TEXT NOT NULL DEFAULT '',
attempt INTEGER NOT NULL DEFAULT 0,
actor_id TEXT NOT NULL DEFAULT '',
actor_kind TEXT NOT NULL DEFAULT '',
principal_id TEXT NOT NULL DEFAULT '',
detail TEXT NOT NULL DEFAULT '',
data TEXT NOT NULL DEFAULT '{}'
);
@@ -48,10 +51,11 @@ func insertEvent(ctx context.Context, execer eventExecer, e events.Event) (int64
data = fmt.Appendf(nil, `{"marshal_error":%q}`, err.Error())
}
res, err := execer.ExecContext(ctx, `
INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, attempt, detail, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, attempt, actor_id, actor_kind, principal_id, detail, data)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
e.At.UTC().Format(time.RFC3339Nano), e.Kind, e.TaskID, e.Repo, e.Issue,
e.Workflow, e.Stage, e.Attempt, clip(e.Detail, 4000), string(data))
e.Workflow, e.Stage, e.Attempt, e.ActorID, e.ActorKind, e.PrincipalID,
clip(e.Detail, 4000), string(data))
if err != nil {
return 0, err
}
@@ -66,7 +70,8 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) {
var e events.Event
var at, data string
if err := rows.Scan(&e.ID, &at, &e.Kind, &e.TaskID, &e.Repo, &e.Issue,
&e.Workflow, &e.Stage, &e.Attempt, &e.Detail, &data); err != nil {
&e.Workflow, &e.Stage, &e.Attempt, &e.ActorID, &e.ActorKind,
&e.PrincipalID, &e.Detail, &data); err != nil {
return nil, err
}
e.At, _ = time.Parse(time.RFC3339Nano, at)
@@ -76,7 +81,7 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) {
return out, rows.Err()
}
const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, attempt, detail, data"
const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, attempt, actor_id, actor_kind, principal_id, detail, data"
// EventsSince returns up to limit events with id > sinceID, oldest
// first -- SSE catch-up and the live feed.
+52
View File
@@ -23,6 +23,10 @@ CREATE TABLE IF NOT EXISTS identity_events (
id INTEGER PRIMARY KEY AUTOINCREMENT, identity_id TEXT NOT NULL, event_type TEXT NOT NULL,
from_lifecycle TEXT NOT NULL, to_lifecycle TEXT NOT NULL, display_name TEXT NOT NULL,
actor_id TEXT NOT NULL, source TEXT NOT NULL, request_id TEXT NOT NULL UNIQUE, at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS identity_subjects (
issuer TEXT NOT NULL, subject TEXT NOT NULL, identity_id TEXT NOT NULL REFERENCES identities(id),
bound_at TEXT NOT NULL, PRIMARY KEY (issuer, subject)
);`
const identityTimeLayout = time.RFC3339Nano
@@ -130,6 +134,54 @@ func (s *Store) Apply(ctx context.Context, id identity.IdentityID, expectedVersi
return next, tx.Commit()
}
// ResolveSubject returns the identity bound to a provider subject, so a
// credential that verified against the provider's keys selects an identity
// archie already knows rather than creating one.
func (s *Store) ResolveSubject(ctx context.Context, subject identity.Subject) (identity.Identity, error) {
value, err := scanIdentity(s.db.QueryRowContext(ctx, `SELECT i.id, i.kind, i.display_name, i.lifecycle, i.version, i.created_at, i.updated_at FROM identities i JOIN identity_subjects b ON b.identity_id=i.id WHERE b.issuer=? AND b.subject=?`, subject.Issuer, subject.Subject))
if errors.Is(err, sql.ErrNoRows) {
return identity.Identity{}, identity.ErrNotFound
}
return value, err
}
// BindSubject binds an identity to the provider subject that asserts it. The
// binding is audited like any other identity mutation: who authorised a caller
// to act as this identity is the question the record has to answer later.
// Rebinding an already-bound subject moves it, because a subject that changed
// hands must resolve to whoever it belongs to now.
func (s *Store) BindSubject(ctx context.Context, id identity.IdentityID, subject identity.Subject, audit identity.Audit) error {
if err := subject.Validate(); err != nil {
return err
}
if audit.ActorID == "" || audit.Source == "" || audit.RequestID == "" {
return fmt.Errorf("%w: audit actor, source, and request ID are required", identity.ErrInvalid)
}
now := audit.At.UTC()
if now.IsZero() {
now = time.Now().UTC()
}
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
current, err := scanIdentity(tx.QueryRowContext(ctx, `SELECT id, kind, display_name, lifecycle, version, created_at, updated_at FROM identities WHERE id=?`, id))
if errors.Is(err, sql.ErrNoRows) {
return identity.ErrNotFound
}
if err != nil {
return err
}
if _, err = tx.ExecContext(ctx, `INSERT INTO identity_subjects(issuer,subject,identity_id,bound_at) VALUES(?,?,?,?) ON CONFLICT(issuer,subject) DO UPDATE SET identity_id=excluded.identity_id, bound_at=excluded.bound_at`, subject.Issuer, subject.Subject, id, now.Format(identityTimeLayout)); err != nil {
return err
}
if err = insertIdentityEvent(ctx, tx, current, identity.Event{IdentityID: id, Type: "bind_subject", From: current.Lifecycle, To: current.Lifecycle, DisplayName: subject.Subject}, audit, now); err != nil {
return err
}
return tx.Commit()
}
func (s *Store) BootstrapIdentities(ctx context.Context, legacyNames []string) error {
values := append([]struct {
id identity.IdentityID
+157
View File
@@ -0,0 +1,157 @@
package store
import (
"context"
"errors"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/events"
)
func bindAudit(requestID string) identity.Audit {
return identity.Audit{ActorID: identity.SystemID, Source: "test", RequestID: requestID, At: time.Now().UTC()}
}
func newTestIdentity(t *testing.T, s *Store, id identity.IdentityID, kind identity.Kind, name string) identity.Identity {
t.Helper()
value, err := identity.New(id, kind, name)
if err != nil {
t.Fatalf("identity.New() error = %v", err)
}
created, err := s.Create(context.Background(), value, bindAudit("create:"+string(id)))
if err != nil {
t.Fatalf("Create() error = %v", err)
}
return created
}
// TestResolveSubjectReturnsTheBoundIdentity: a verified provider subject selects
// the identity it is bound to, which is what lets a credential resolve to a
// record archie already knows rather than creating one.
func TestResolveSubjectReturnsTheBoundIdentity(t *testing.T) {
s := openTest(t)
ctx := context.Background()
agent := newTestIdentity(t, s, identity.IdentityID("30000000-0000-5000-8000-000000000001"), identity.KindBot, "archie-agent")
subject := identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "archie"}
if err := s.BindSubject(ctx, agent.ID, subject, bindAudit("bind:1")); err != nil {
t.Fatalf("BindSubject() error = %v", err)
}
got, err := s.ResolveSubject(ctx, subject)
if err != nil {
t.Fatalf("ResolveSubject() error = %v", err)
}
if got.ID != agent.ID || got.Kind != identity.KindBot {
t.Fatalf("ResolveSubject() = %+v, want %+v", got, agent)
}
}
// TestResolveSubjectIsKeyedOnIssuerAndSubject: the same subject string from a
// different issuer is a different caller, so it must not resolve.
func TestResolveSubjectIsKeyedOnIssuerAndSubject(t *testing.T) {
s := openTest(t)
ctx := context.Background()
agent := newTestIdentity(t, s, identity.IdentityID("30000000-0000-5000-8000-000000000002"), identity.KindBot, "archie-agent")
bound := identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "archie"}
if err := s.BindSubject(ctx, agent.ID, bound, bindAudit("bind:2")); err != nil {
t.Fatalf("BindSubject() error = %v", err)
}
others := []struct {
name string
subject identity.Subject
}{
{"another issuer, same subject", identity.Subject{Issuer: "https://elsewhere.example", Subject: "archie"}},
{"same issuer, another subject", identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "someone-else"}},
}
for _, tc := range others {
t.Run(tc.name, func(t *testing.T) {
if _, err := s.ResolveSubject(ctx, tc.subject); !errors.Is(err, identity.ErrNotFound) {
t.Fatalf("ResolveSubject() error = %v, want %v", err, identity.ErrNotFound)
}
})
}
}
// TestBindSubjectMovesAnAlreadyBoundSubject: when a subject changes hands it
// resolves to whoever holds it now, so a reassignment cannot leave two identities
// claiming one provider subject.
func TestBindSubjectMovesAnAlreadyBoundSubject(t *testing.T) {
s := openTest(t)
ctx := context.Background()
first := newTestIdentity(t, s, identity.IdentityID("30000000-0000-5000-8000-000000000003"), identity.KindBot, "first-agent")
second := newTestIdentity(t, s, identity.IdentityID("30000000-0000-5000-8000-000000000004"), identity.KindBot, "second-agent")
subject := identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "archie"}
if err := s.BindSubject(ctx, first.ID, subject, bindAudit("bind:3")); err != nil {
t.Fatalf("BindSubject() error = %v", err)
}
if err := s.BindSubject(ctx, second.ID, subject, bindAudit("bind:4")); err != nil {
t.Fatalf("rebind error = %v", err)
}
got, err := s.ResolveSubject(ctx, subject)
if err != nil {
t.Fatalf("ResolveSubject() error = %v", err)
}
if got.ID != second.ID {
t.Fatalf("ResolveSubject() = %s, want %s", got.ID, second.ID)
}
}
func TestBindSubjectRequiresAuditAndAKnownIdentity(t *testing.T) {
s := openTest(t)
ctx := context.Background()
subject := identity.Subject{Issuer: "https://auth.catlow.cloud", Subject: "archie"}
if err := s.BindSubject(ctx, identity.SystemID, subject, identity.Audit{}); err == nil {
t.Fatal("BindSubject() accepted a binding with no audit")
}
if err := s.BindSubject(ctx, identity.IdentityID("does-not-exist"), subject, bindAudit("bind:5")); !errors.Is(err, identity.ErrNotFound) {
t.Fatalf("BindSubject() error = %v, want %v", err, identity.ErrNotFound)
}
if err := s.BindSubject(ctx, identity.SystemID, identity.Subject{}, bindAudit("bind:6")); err == nil {
t.Fatal("BindSubject() accepted an incomplete subject")
}
}
// TestEventAttributionSurvivesTheRoundTrip: the attributions are only useful if
// they come back out of the store, so a reader can answer who acted and whose
// authority they used.
func TestEventAttributionSurvivesTheRoundTrip(t *testing.T) {
s := openTest(t)
ctx := context.Background()
inserted, err := s.InsertEvent(ctx, events.Event{
Kind: events.KindAgentApproved,
TaskID: 11,
ActorID: "30000000-0000-5000-8000-000000000001",
ActorKind: string(identity.KindBot),
PrincipalID: "30000000-0000-5000-8000-000000000009",
Detail: "approved by an agent",
})
if err != nil {
t.Fatalf("InsertEvent() error = %v", err)
}
got, err := s.TaskEvents(ctx, 11)
if err != nil {
t.Fatalf("TaskEvents() error = %v", err)
}
if len(got) != 1 {
t.Fatalf("TaskEvents() returned %d events, want 1", len(got))
}
e := got[0]
if e.ID != inserted {
t.Fatalf("event id = %d, want %d", e.ID, inserted)
}
if e.Kind != events.KindAgentApproved {
t.Fatalf("kind = %q, want %q", e.Kind, events.KindAgentApproved)
}
if e.ActorID == "" || e.ActorKind != string(identity.KindBot) || e.PrincipalID == "" {
t.Fatalf("attribution did not survive the round trip: %+v", e)
}
}
+3
View File
@@ -126,6 +126,9 @@ func migrateTasks(ctx context.Context, db *sql.DB) error {
{"bindings", "owner", `ALTER TABLE bindings ADD COLUMN owner TEXT NOT NULL DEFAULT ''`},
{"bindings", "repo", `ALTER TABLE bindings ADD COLUMN repo TEXT NOT NULL DEFAULT ''`},
{"events", "attempt", `ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`},
{"events", "actor_id", `ALTER TABLE events ADD COLUMN actor_id TEXT NOT NULL DEFAULT ''`},
{"events", "actor_kind", `ALTER TABLE events ADD COLUMN actor_kind TEXT NOT NULL DEFAULT ''`},
{"events", "principal_id", `ALTER TABLE events ADD COLUMN principal_id TEXT NOT NULL DEFAULT ''`},
}
for _, migration := range migrations {
present := columns
+2 -1
View File
@@ -15,6 +15,7 @@ import (
"testing"
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
@@ -81,7 +82,7 @@ func (d *daemonActions) ApplyChatTaskAction(
d.publish(),
d.srv.logf,
)
if err := service.Apply(ctx, identity, id, action); err != nil {
if err := service.Apply(ctx, identity, taskactions.Actor{}, id, action); err != nil {
return gateway.TaskActionResult{}, err
}
return gateway.TaskActionResult{TaskID: id, Action: string(action)}, nil
+1 -1
View File
@@ -15,5 +15,5 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
Defaulting to \`null\`.`),null)}function Tx(e){return Cx(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${bx}\`.`),bx)}var Ex=N({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:bx},getValueLabel:{type:Function,required:!1,default:(e,t)=>Cx(e)?`${Math.round(e/t*bx)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;X();let i=yh(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=yh(n,`max`,r,{passive:n.max===void 0});M(()=>i.value,async e=>{let t=wx(e,n.max);t!==e&&(await ar(),i.value=t)},{immediate:!0}),M(()=>n.max,e=>{let t=Tx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=G(()=>Um(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Sx({modelValue:i,max:a,progressState:o}),(e,t)=>(L(),z(A(Z),{"as-child":e.asChild,as:e.as,"aria-valuemax":A(a),"aria-valuemin":0,"aria-valuenow":Cx(A(i))?A(i):void 0,"aria-valuetext":e.getValueText?.(A(i),A(a)),"aria-label":e.getValueLabel(A(i),A(a)),role:`progressbar`,"data-state":o.value,"data-value":A(i)??void 0,"data-max":A(a)},{default:j(()=>[F(e.$slots,`default`,{modelValue:A(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Dx=N({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=xx();return X(),(e,r)=>(L(),z(A(Z),W(t,{"data-state":A(n).progressState.value,"data-value":A(n).modelValue?.value??void 0,"data-max":A(n).max.value}),{default:j(()=>[F(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Ox=[` `,`Enter`,`ArrowUp`,`ArrowDown`],kx=[` `,`Enter`];function Ax(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>jx(e,t,n)):jx(e,t,n)}function jx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Rm(e,t)}function Mx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Nx=[`value`],[Px,Fx]=Bm(`SelectRoot`),Ix=N({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=En(n),c=yh(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=yh(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=k(),d=k(),f=k({x:0,y:0}),p=G(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Um(c.value));D_({isProvider:!0});let m=Fh(s),h=Bh(u),g=k(new Set),_=G(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>jx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Ax(e,t.value,n.by))}return Fx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(L(),z(A(B_),null,{default:j(()=>[F(e.$slots,`default`,{modelValue:A(c),open:A(l)}),A(h)&&e.name?(L(),z(Lx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:A(o),required:A(i),name:e.name,autocomplete:e.autocomplete,disabled:A(a),value:A(c)},{default:j(()=>[A(Um)(A(c))?(L(),R(`option`,{key:0,value:e.nullableValue},null,8,Nx)):U(`v-if`,!0),(L(!0),R(I,null,P(Array.from(g.value),e=>(L(),R(`option`,W({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):U(`v-if`,!0)]),_:3}))}}),Lx=N({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=k(),r=Px();M(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:nT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>nT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=iT(c),u=e+1<n.length?iT(n[e+1]):null;if(l&&u&&aT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=iT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>nT(e)),rows:r.map(e=>e.map(e=>nT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:nT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:nT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
`)}),t}function iT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function aT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var oT={class:`[overflow-wrap:anywhere]`},sT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},cT={class:`font-mono text-[0.85em]`},lT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},uT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},dT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},fT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},pT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},mT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},hT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},gT={key:8,class:`mb-2.5 last:mb-0`},_T=N({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>rT(t.text));return(e,t)=>(L(),R(`div`,oT,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,sT,[B(`code`,cT,O(e.code),1)])):e.kind===`table`?(L(),R(`table`,lT,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(eT,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(eT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,uT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,dT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,fT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,pT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,mT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,hT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,gT,[V(eT,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),vT={class:`truncate`},yT=N({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ma(`RouterLink`);return L(),z(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[V(A(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,vT,O(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),bT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},xT={class:`font-semibold text-foreground`},ST={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},CT=N({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(L(),z(yT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,bT,[V(A(Kd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,xT,O(n.value),1),r.value?(L(),R(`code`,ST,O(r.value),1)):U(``,!0),B(`span`,{class:D(A(J)(`text-fg-muted`,i.value&&`text-danger`))},O(a.value),3)]))}}),wT={key:0,class:`mb-2 grid gap-0.5 text-xs`},TT={key:2,class:`whitespace-pre-wrap`},ET=N({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:D([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:D(A(J)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(L(),R(`div`,wT,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(CT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.assistant?(L(),z(_T,{key:1,text:e.text},null,8,[`text`])):(L(),R(`div`,TT,O(e.text),1)),F(t.$slots,`default`)],2)],2))}}),DT={class:`w-full self-center justify-self-center py-6 text-center`},OT={class:`grid gap-2`},kT=[`onClick`],AT=N({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(L(),R(`div`,DT,[t[0]||=B(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`)}),t}function iT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function aT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var oT={class:`[overflow-wrap:anywhere]`},sT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},cT={class:`font-mono text-[0.85em]`},lT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},uT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},dT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},fT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},pT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},mT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},hT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},gT={key:8,class:`mb-2.5 last:mb-0`},_T=N({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>rT(t.text));return(e,t)=>(L(),R(`div`,oT,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,sT,[B(`code`,cT,O(e.code),1)])):e.kind===`table`?(L(),R(`table`,lT,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(eT,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(eT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,uT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,dT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,fT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,pT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,mT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,hT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,gT,[V(eT,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),vT={class:`truncate`},yT=N({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ma(`RouterLink`);return L(),z(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[V(A(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,vT,O(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),bT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},xT={class:`font-semibold text-foreground`},ST={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},CT=N({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(L(),z(yT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,bT,[V(A(Kd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,xT,O(n.value),1),r.value?(L(),R(`code`,ST,O(r.value),1)):U(``,!0),B(`span`,{class:D(A(J)(`text-fg-muted`,i.value&&`text-danger`))},O(a.value),3)]))}}),wT={key:0,class:`mb-2 grid gap-0.5 text-xs`},TT={key:2,class:`whitespace-pre-wrap`},ET=N({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:D([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:D(A(J)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(L(),R(`div`,wT,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(CT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.assistant?(L(),z(_T,{key:1,text:e.text},null,8,[`text`])):(L(),R(`div`,TT,O(e.text),1)),F(t.$slots,`default`)],2)],2))}}),DT={class:`w-full self-center justify-self-center py-6 text-center`},OT={class:`grid gap-2`},kT=[`onClick`],AT=N({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(L(),R(`div`,DT,[t[0]||=B(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>cA?`${n.slice(0,cA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var uA=[`title`],dA=N({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>Dk(n.event)),a=G(()=>lA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?vO(n.event.at):`—`);return(e,t)=>(L(),z(A(aA),{class:D(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[du(lu(o,[`prevent`]),[`enter`]),du(lu(o,[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[H(O(n.event.kind||n.event.type||`event`),1)]),_:1}),V(A($),{class:`font-mono`},{default:j(()=>[H(O(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},O(a.value.text),9,uA)]),_:1}),V(A($),null,{default:j(()=>[H(O(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}}),fA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},pA=N({__name:`LiveActivityCard`,setup(e){let t=$T(),{activity:n,streamKind:r,streamState:i}=ad(ek());function a(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(A(uO),null,{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...t[0]||=[H(`Live activity`,-1)]]),_:1}),V(A(pO),null,{default:j(()=>[...t[1]||=[H(`Last 50, newest first`,-1)]]),_:1}),V(A(dO),null,{default:j(()=>[V(A(XD),{variant:A(r)},{default:j(()=>[H(O(A(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(A(fO),null,{default:j(()=>[B(`div`,fA,[V(A(rA),null,{default:j(()=>[V(A(sA),null,{default:j(()=>[V(A(aA),null,{default:j(()=>[V(A(oA),null,{default:j(()=>[...t[2]||=[H(`Event`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[3]||=[H(`Task`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[4]||=[H(`Detail`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[5]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(A(iA),null,{default:j(()=>[A(n).length?(L(!0),R(I,{key:1},P(A(n),(e,t)=>(L(),z(dA,{key:t,event:e,onOpen:a},null,8,[`event`]))),128)):(L(),z(A(aA),{key:0},{default:j(()=>[V(A($),{colspan:`4`},{default:j(()=>[V(A(HD),null,{default:j(()=>[V(A(GD),null,{default:j(()=>[V(A(JD),null,{default:j(()=>[...t[6]||=[H(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1}))]),_:1})]),_:1})])]),_:1})]),_:1}))}}),mA=N({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=QS(t,`class`);return(e,r)=>(L(),z(A(Ex),W({"data-slot":`progress`},A(n),{class:A(J)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:j(()=>[V(A(Dx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ve(`transform: translateX(-${100-(t.modelValue??0)}%);`)},null,8,[`style`])]),_:1},16,[`class`]))}}),hA=`archie.setup-complete.dismissed.v1`;function gA(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(hA),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function _A(e=globalThis.localStorage){e?.setItem?.(hA,`1`)}var vA={class:`text-lg font-semibold text-link`},yA={class:`flex flex-col gap-3`},bA={key:0,class:`mt-0.5 text-xs text-fg-subtle`},xA=N({__name:`SetupPanel`,setup(e){let t=k(gA(bk.value));M(bk,()=>{t.value=gA(bk.value)});let n=G(()=>bk.value?.steps??[]),r=G(()=>{let e=n.value.length;return e?Math.round((e-t.value.remaining.length)/e*100):0});function i(){_A(),t.value=gA(bk.value)}return(e,a)=>t.value.kind===`incomplete`?(L(),z(A(uO),{key:0},{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...a[0]||=[H(`Finish setting up`,-1)]]),_:1}),V(A(pO),null,{default:j(()=>[...a[1]||=[H(`Archie needs these before it can work on its own.`,-1)]]),_:1}),V(A(dO),null,{default:j(()=>[B(`span`,vA,O(r.value)+`%`,1)]),_:1})]),_:1}),V(A(fO),null,{default:j(()=>[V(A(mA),{"model-value":r.value,class:`mb-4`},null,8,[`model-value`]),B(`ul`,yA,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(`li`,{key:t,class:`flex items-start gap-3`},[B(`span`,{class:D([`mt-px grid size-[18px] flex-none place-items-center rounded-full border-[1.5px] border-border-strong text-xs text-fg-subtle`,e.done?`border-transparent bg-ok-soft text-ok`:``])},[e.done?(L(),z(A(bd),{key:0,class:`size-3`})):U(``,!0)],2),B(`div`,null,[B(`div`,{class:D([`text-sm`,e.done?`text-fg-muted line-through`:``])},O(e.title),3),e.detail?(L(),R(`div`,bA,O(e.detail),1)):U(``,!0)])]))),128))])]),_:1})]),_:1})):t.value.kind===`complete`?(L(),z(A(uO),{key:1},{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...a[2]||=[H(`Setup complete`Line truncated
+2
View File
@@ -23,6 +23,8 @@ const taskKinds = new Set([
"pr_rejected",
"human_approved",
"human_rejected",
"agent_approved",
"agent_rejected",
"changes_captured",
"config_captured",
"work_request_submitted",