feat(access): scoped canary grant replaces instance-admin CANARY_TOKEN (#1727)
Quality / check (push) Successful in 3m49s
deploy / gate (push) Successful in 4m48s
deploy / archied-image (push) Successful in 2m55s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped

The canary now authenticates as a dedicated service-account identity in the
system org whose only grant is access.CalaryGrantPolicy: read the signal
endpoints (chat update, alerts, logs, tasks), read and write the
update-settings resource, and trigger an update install. CANARY_TOKEN no
longer carries instance admin; DEPLOY_TOKEN stays CI-only.

- authorize: POST /api/chat/update/install and /defer map to
  update on Object::"update" (dashboard) instead of run on any workflow,
  so the grant can cover installs without granting workflow runs
- accounts: active service-account identities may authenticate with bearer
  tokens (CanAct), not just users
- new POST /api/identities/{id}/tokens (behind manage_identities) mints a
  token for a named non-user identity; new AccountService RPC
  BindIdentityPersonalToken backs it remotely, refusing user-kind targets,
  with the caller recorded as audit actor
- engine tests pin the grant's exact allow/deny surface

RELEASING.md documents the one-time setup. task check passes on this tree.
This commit is contained in:
sam committed 2026-11-02 06:03:41 +11:00
1 parent 5356745968
commit c180a2debb
16 files changed
+978 -231

No files matched your search

+40 -2
View File
@@ -179,11 +179,49 @@ by hand.
| Name | Kind | Holds |
| --- | --- | --- |
| `CANARY_URL` | Actions variable | the canary's dashboard URL; unset disables the canary steps |
| `CANARY_TOKEN` | Actions secret | a personal API token on the canary with instance admin |
| `CANARY_TOKEN` | Actions secret | an API token bound to a dedicated `service_account` identity on the canary, carrying only the canary grant policy (see below) — never instance admin |
| `CANARY_WINDOW` | Actions variable | optional `-window` override for `canary check`; unset is 24h |
| `DEPLOY_TOKEN` | Actions secret | registry and repository write, for publishing, promoting and the release push |
| `DEPLOY_TOKEN` | Actions secret | registry and repository write, for publishing, promoting and the release push; stays CI-only, promotion runs in CI and never on the host |
| `RELEASE_SIGNING_KEY` | Actions secret | the release signing seed |
#### Setting up `CANARY_TOKEN` once
`CANARY_TOKEN` is a bearer token for a dedicated service-account identity in
the system org whose only grant is the canary policy
(`access.CanaryGrantPolicy`): read the signal endpoints (`GET /api/chat/update`,
`GET /api/alerts`, `GET /api/logs`, `GET /api/tasks`), read and write the
`update-settings` resource, and trigger an update install
(`POST /api/chat/update/install`). It carries no other rights, and instance
admin is never needed. With an instance-admin token (for example the operator
session), run against the canary host:
```bash
# 1. Create the service-account identity in the system org.
curl -X POST "$CANARY_URL/api/identities" -H "Authorization: Bearer $ADMIN" \
-H 'Content-Type: application/json' \
-d '{"kind":"service_account","display_name":"ci-canary"}'
# -> {"id":"<canary-identity-id>", ...}
# 2. Issue its token (shown exactly once).
curl -X POST "$CANARY_URL/api/identities/<canary-identity-id>/tokens" \
-H "Authorization: Bearer $ADMIN" -H 'Content-Type: application/json' \
-d '{"name":"ci-canary","days":90}'
# -> {"id":"<token-hash>","token":"archie_pat_..."} -- store the token value as the CANARY_TOKEN secret
# 3. Install the grant, scoped to that identity. The policy's org is pinned
# to the caller's org (org-sys for the instance admin), so the body needs
# no org field.
curl -X PUT "$CANARY_URL/api/access/policies" -H "Authorization: Bearer $ADMIN" \
-H 'Content-Type: application/json' \
-d '{"id":"org-canary-grant","level":"org","text":"permit(principal, action, resource) when {\n resource.org == principal.org &&\n principal == Archie::Identity::\"<canary-identity-id>\" &&\n (\n (action == Archie::Action::\"read\" && [\"dashboard\", \"task\"].contains(resource.kind)) ||\n (action == Archie::Action::\"read\" && resource == Archie::Object::\"update-settings\") ||\n (action == Archie::Action::\"update\" && resource == Archie::Object::\"update\") ||\n (action == Archie::Action::\"manage_identities\" && resource == Archie::Object::\"update-settings\")\n )\n};"}'
```
The policy text is exactly `access.CanaryGrantPolicy(org-sys, <canary-identity-id>)`
from `internal/domain/access/canary.go`; the curl body above is that text with
the identity id filled in. The canary needs no other rights: `GET
/health/detailed` is unauthenticated, and every other call it makes is covered
by the grant.
The runner must reach `CANARY_URL`. Without a canary a release stays on `next`
until promoted by hand, under the same refusals:
File diff suppressed because it is too large. Load diff
@@ -38,6 +38,7 @@ const (
AccountService_AddPersonalToken_FullMethodName = "/state.v1.AccountService/AddPersonalToken"
AccountService_ListPersonalTokens_FullMethodName = "/state.v1.AccountService/ListPersonalTokens"
AccountService_RevokePersonalToken_FullMethodName = "/state.v1.AccountService/RevokePersonalToken"
AccountService_BindIdentityPersonalToken_FullMethodName = "/state.v1.AccountService/BindIdentityPersonalToken"
)
// AccountServiceClient is the client API for AccountService service.
@@ -65,6 +66,12 @@ type AccountServiceClient interface {
AddPersonalToken(ctx context.Context, in *AddPersonalTokenRequest, opts ...grpc.CallOption) (*AddPersonalTokenResponse, error)
ListPersonalTokens(ctx context.Context, in *ListPersonalTokensRequest, opts ...grpc.CallOption) (*ListPersonalTokensResponse, error)
RevokePersonalToken(ctx context.Context, in *RevokePersonalTokenRequest, opts ...grpc.CallOption) (*RevokePersonalTokenResponse, error)
// BindIdentityPersonalToken binds a personal token to a NAMED identity
// instead of the caller's principal, which is how a service account gets
// its bearer credential. Only non-user targets are accepted: a person's
// token comes from AddPersonalToken. The audit actor is the caller's
// principal, never a request field.
BindIdentityPersonalToken(ctx context.Context, in *BindIdentityPersonalTokenRequest, opts ...grpc.CallOption) (*BindIdentityPersonalTokenResponse, error)
}
type accountServiceClient struct {
@@ -265,6 +272,16 @@ func (c *accountServiceClient) RevokePersonalToken(ctx context.Context, in *Revo
return out, nil
}
func (c *accountServiceClient) BindIdentityPersonalToken(ctx context.Context, in *BindIdentityPersonalTokenRequest, opts ...grpc.CallOption) (*BindIdentityPersonalTokenResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(BindIdentityPersonalTokenResponse)
err := c.cc.Invoke(ctx, AccountService_BindIdentityPersonalToken_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// AccountServiceServer is the server API for AccountService service.
// All implementations must embed UnimplementedAccountServiceServer
// for forward compatibility.
@@ -290,6 +307,12 @@ type AccountServiceServer interface {
AddPersonalToken(context.Context, *AddPersonalTokenRequest) (*AddPersonalTokenResponse, error)
ListPersonalTokens(context.Context, *ListPersonalTokensRequest) (*ListPersonalTokensResponse, error)
RevokePersonalToken(context.Context, *RevokePersonalTokenRequest) (*RevokePersonalTokenResponse, error)
// BindIdentityPersonalToken binds a personal token to a NAMED identity
// instead of the caller's principal, which is how a service account gets
// its bearer credential. Only non-user targets are accepted: a person's
// token comes from AddPersonalToken. The audit actor is the caller's
// principal, never a request field.
BindIdentityPersonalToken(context.Context, *BindIdentityPersonalTokenRequest) (*BindIdentityPersonalTokenResponse, error)
mustEmbedUnimplementedAccountServiceServer()
}
@@ -357,6 +380,9 @@ func (UnimplementedAccountServiceServer) ListPersonalTokens(context.Context, *Li
func (UnimplementedAccountServiceServer) RevokePersonalToken(context.Context, *RevokePersonalTokenRequest) (*RevokePersonalTokenResponse, error) {
return nil, status.Error(codes.Unimplemented, "method RevokePersonalToken not implemented")
}
func (UnimplementedAccountServiceServer) BindIdentityPersonalToken(context.Context, *BindIdentityPersonalTokenRequest) (*BindIdentityPersonalTokenResponse, error) {
return nil, status.Error(codes.Unimplemented, "method BindIdentityPersonalToken not implemented")
}
func (UnimplementedAccountServiceServer) mustEmbedUnimplementedAccountServiceServer() {}
func (UnimplementedAccountServiceServer) testEmbeddedByValue() {}
@@ -720,6 +746,24 @@ func _AccountService_RevokePersonalToken_Handler(srv interface{}, ctx context.Co
return interceptor(ctx, in, info, handler)
}
func _AccountService_BindIdentityPersonalToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BindIdentityPersonalTokenRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AccountServiceServer).BindIdentityPersonalToken(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: AccountService_BindIdentityPersonalToken_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AccountServiceServer).BindIdentityPersonalToken(ctx, req.(*BindIdentityPersonalTokenRequest))
}
return interceptor(ctx, in, info, handler)
}
// AccountService_ServiceDesc is the grpc.ServiceDesc for AccountService service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -803,6 +847,10 @@ var AccountService_ServiceDesc = grpc.ServiceDesc{
MethodName: "RevokePersonalToken",
Handler: _AccountService_RevokePersonalToken_Handler,
},
{
MethodName: "BindIdentityPersonalToken",
Handler: _AccountService_BindIdentityPersonalToken_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "state/v1/account.proto",
+29
View File
@@ -0,0 +1,29 @@
package access
import "github.com/samcharles93/archie-core/internal/domain/org"
// CanaryGrantID is the ID the canary's scoped grant is known by in the policy
// store and in denial records. A stored policy must not reuse it: the store's
// seeding and the reset command overwrite shipped IDs, and this one is
// installed by the operator from CanaryGrantPolicy's text.
const CanaryGrantID = "org-canary-grant"
// CanaryGrantPolicy is the grant a CI canary carries instead of instance
// admin: exactly one named identity may read the dashboard's signal surface
// (chat update, alerts, logs, tasks), read and write the update-settings
// resource, and trigger an update install or deferral. Every clause is
// guarded by the resource belonging to the principal's own org, which the
// engine enforces structurally anyway.
func CanaryGrantPolicy(orgID org.OrgID, identityID string) Policy {
text := `permit(principal, action, resource) when {
resource.org == principal.org &&
principal == Archie::Identity::"` + identityID + `" &&
(
(action == Archie::Action::"read" && ["dashboard", "task"].contains(resource.kind)) ||
(action == Archie::Action::"read" && resource == Archie::Object::"update-settings") ||
(action == Archie::Action::"update" && resource == Archie::Object::"update") ||
(action == Archie::Action::"manage_identities" && resource == Archie::Object::"update-settings")
)
};`
return Policy{ID: CanaryGrantID, Level: LevelOrg, OrgID: orgID, Text: text}
}
+28
View File
@@ -0,0 +1,28 @@
package access
import (
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// TestCanaryGrantPolicy pins the shape of the canary grant: it names exactly
// the one identity it is built for, scoped to the org it serves, so a token
// carrying it cannot act as anyone else or reach another org.
func TestCanaryGrantPolicy(t *testing.T) {
p := CanaryGrantPolicy(org.DefaultOrgID, "canary-svc")
if err := p.Validate(); err != nil {
t.Fatalf("Validate: %v", err)
}
if p.ID != CanaryGrantID || p.Level != LevelOrg || p.OrgID != org.DefaultOrgID {
t.Fatalf("policy = %+v, want ID %q at org level in %q", p, CanaryGrantID, org.DefaultOrgID)
}
if !strings.Contains(p.Text, `principal == Archie::Identity::"canary-svc"`) {
t.Fatalf("text does not name the canary identity:\n%s", p.Text)
}
other := CanaryGrantPolicy(org.DefaultOrgID, "another")
if strings.Contains(other.Text, "canary-svc") || !strings.Contains(other.Text, `Archie::Identity::"another"`) {
t.Fatalf("grant for another identity must name that identity only:\n%s", other.Text)
}
}
@@ -112,3 +112,73 @@ func TestWorkspaceEnvironment(t *testing.T) {
})
}
}
// TestCanaryGrant pins the scoped canary grant: the one identity it names, with
// no role, may read the signal surface, read and write update-settings, and
// trigger an install -- and nothing else, neither for it nor for anyone else.
func TestCanaryGrant(t *testing.T) {
const canaryID = identity.IdentityID("canary-svc")
grant := access.CanaryGrantPolicy(org.DefaultOrgID, string(canaryID))
engine := New(append(access.ShippedOrgPolicies(org.DefaultOrgID), grant))
if len(engine.Problems()) != 0 {
t.Fatalf("problems = %v, want the canary grant to compile", engine.Problems())
}
canary := access.Principal{IdentityID: canaryID, Org: org.DefaultOrgID}
other := access.Principal{IdentityID: "someone-else", Org: org.DefaultOrgID}
at := func(kind access.ResourceKind, id string) access.Resource {
return access.Resource{Kind: kind, ID: id, Org: org.DefaultOrgID}
}
tests := []struct {
name string
principal access.Principal
action access.Action
resource access.Resource
allowed bool
}{
{"read the dashboard", canary, access.ActionRead, at(access.KindDashboard, ""), true},
{"read tasks", canary, access.ActionRead, at(access.KindTask, ""), true},
{"read one task", canary, access.ActionRead, at(access.KindTask, "7"), true},
{"read update-settings", canary, access.ActionRead, at(access.KindPolicy, "update-settings"), true},
{"install an update", canary, access.ActionUpdate, at(access.KindDashboard, "update"), true},
{"replace update-settings", canary, access.ActionManageIdentities, at(access.KindPolicy, "update-settings"), true},
{"read a secret", canary, access.ActionReadSecret, at(access.KindSecret, "github-token"), false},
{"delete a task", canary, access.ActionDelete, at(access.KindTask, "7"), false},
{"manage policies", canary, access.ActionManagePolicies, at(access.KindPolicy, "org-role-read"), false},
{"run a workflow", canary, access.ActionRun, at(access.KindWorkflow, "triage"), false},
{"create anything", canary, access.ActionCreate, at(access.KindTask, ""), false},
{"update another object", canary, access.ActionUpdate, at(access.KindDashboard, "other"), false},
{"read another object", canary, access.ActionRead, at(access.KindPolicy, "other-policy"), false},
{"manage identities on another object", canary, access.ActionManageIdentities, at(access.KindIdentity, "someone-else"), false},
{"read logs", canary, access.ActionReadLogs, at(access.KindTask, "7"), false},
{"read the audit feed", canary, access.ActionReadAudit, at(access.KindAudit, ""), false},
{"a resource of another org", canary, access.ActionRead, access.Resource{Kind: access.KindDashboard, Org: "acme"}, false},
{"another identity reads the dashboard", other, access.ActionRead, at(access.KindDashboard, ""), false},
{"another identity installs an update", other, access.ActionUpdate, at(access.KindDashboard, "update"), false},
{"another identity replaces update-settings", other, access.ActionManageIdentities, at(access.KindPolicy, "update-settings"), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := engine.Authorize(tt.principal, tt.action, tt.resource, access.Context{})
if got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
}
})
}
}
// TestCanaryGrantValidates pins that the canary grant passes the domain's
// structural check and the engine's schema validation, so it can be installed
// through the policy store.
func TestCanaryGrantValidates(t *testing.T) {
grant := access.CanaryGrantPolicy(org.DefaultOrgID, "canary-svc")
if err := grant.Validate(); err != nil {
t.Fatalf("Validate: %v", err)
}
engine := New([]access.Policy{grant})
if err := engine.Validate(grant); err != nil {
t.Fatalf("engine Validate: %v", err)
}
if len(engine.Problems()) != 0 {
t.Fatalf("problems = %v, want none", engine.Problems())
}
}
@@ -90,6 +90,40 @@ func (s *accountServer) RevokePersonalToken(ctx context.Context, r *pb.RevokePer
return &pb.RevokePersonalTokenResponse{}, nil
}
// BindIdentityPersonalToken binds a token to a named non-user identity, the
// credential a service account acts with. The audit actor is the caller's
// principal, so the request never names who did it.
func (s *accountServer) BindIdentityPersonalToken(ctx context.Context, r *pb.BindIdentityPersonalTokenRequest) (*pb.BindIdentityPersonalTokenResponse, error) {
if s.deps.PersonalTokens == nil {
return nil, status.Error(codes.Unavailable, "personal tokens unavailable")
}
if s.deps.Identities == nil {
return nil, status.Error(codes.Unavailable, "identity store unavailable")
}
caller, ok := access.PrincipalFromContext(ctx)
if !ok || caller.IdentityID == "" {
return nil, status.Error(codes.Unauthenticated, "binding an identity token requires a principal")
}
target, err := s.deps.Identities.Get(ctx, identity.IdentityID(r.GetIdentityId()))
if err != nil {
return nil, s.identityStatus(ctx, err)
}
if target.Kind == identity.KindUser {
return nil, s.identityStatus(ctx, fmt.Errorf("%w: personal tokens belong to a signed-in person", identity.ErrInvalid))
}
if !target.CanAct() {
return nil, s.identityStatus(ctx, fmt.Errorf("%w: identity is not active", identity.ErrIllegalTransition))
}
subject, err := tokenSubject(r.GetId())
if err != nil {
return nil, err
}
if err := s.deps.PersonalTokens.BindPersonalToken(ctx, target.ID, subject, r.GetName(), optionalTime(r.GetExpiresAt()), tokenAudit(ctx, caller.IdentityID, "bind", r.GetId())); err != nil {
return nil, s.identityStatus(ctx, err)
}
return &pb.BindIdentityPersonalTokenResponse{}, nil
}
func (c *Client) AddPersonalToken(ctx context.Context, subject identity.Subject, name string, expiresAt *time.Time) error {
_, err := c.account.AddPersonalToken(ctx, &pb.AddPersonalTokenRequest{Id: subject.Subject, Name: name, ExpiresAt: optionalTimestamp(expiresAt)})
return identityClientError(err)
@@ -115,6 +149,15 @@ func (c *Client) RevokePersonalToken(ctx context.Context, id string) error {
return identityClientError(err)
}
// BindPersonalToken binds a token to a named identity rather than the caller's
// principal. The audit argument is accepted for the caller-side contract but
// never sent: the store attributes the bind to the caller's own principal, so
// a request cannot claim an actor.
func (c *Client) BindPersonalToken(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, _ identity.Audit) error {
_, err := c.account.BindIdentityPersonalToken(ctx, &pb.BindIdentityPersonalTokenRequest{IdentityId: string(id), Id: subject.Subject, Name: name, ExpiresAt: optionalTimestamp(expiresAt)})
return identityClientError(err)
}
func optionalTimestamp(t *time.Time) *timestamppb.Timestamp {
if t == nil {
return nil
@@ -6,6 +6,10 @@ import (
"testing"
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/timestamppb"
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
@@ -49,3 +53,88 @@ func TestPersonalTokenOwner(t *testing.T) {
})
}
}
type bindCalls struct {
identity.PersonalTokenStore
bound bool
id identity.IdentityID
subject identity.Subject
name string
expires *time.Time
audit identity.Audit
}
func (b *bindCalls) BindPersonalToken(_ context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error {
b.bound, b.id, b.subject, b.name, b.expires, b.audit = true, id, subject, name, expiresAt, audit
return nil
}
type bindIdentityRepo struct {
identity.Repository
values map[identity.IdentityID]identity.Identity
}
func (r bindIdentityRepo) Get(_ context.Context, id identity.IdentityID) (identity.Identity, error) {
if value, ok := r.values[id]; ok {
return value, nil
}
return identity.Identity{}, identity.ErrNotFound
}
// TestBindIdentityPersonalToken pins the named-identity bind: a service
// account gets the token with the caller as audit actor, while a user target,
// an unknown or inactive identity, a malformed token id and a caller with no
// principal are all refused without binding.
func TestBindIdentityPersonalToken(t *testing.T) {
id := strings.Repeat("ab", 32)
sa := identity.Identity{ID: "sa1", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleActive}
user := identity.Identity{ID: "u1", Kind: identity.KindUser, DisplayName: "Alice", Lifecycle: identity.LifecycleActive}
suspended := identity.Identity{ID: "sa2", Kind: identity.KindBot, DisplayName: "Old", Lifecycle: identity.LifecycleSuspended}
repo := bindIdentityRepo{values: map[identity.IdentityID]identity.Identity{sa.ID: sa, user.ID: user, suspended.ID: suspended}}
tests := []struct {
name string
target identity.IdentityID
tokenID string
noPrincipal bool
wantCode codes.Code
wantBound bool
}{
{"service account binds with the caller as actor", sa.ID, id, false, codes.OK, true},
{"user target is refused", user.ID, id, false, codes.FailedPrecondition, false},
{"unknown identity is refused", "nope", id, false, codes.NotFound, false},
{"inactive identity is refused", suspended.ID, id, false, codes.FailedPrecondition, false},
{"malformed token id is refused", sa.ID, "not-hex", false, codes.FailedPrecondition, false},
{"no principal is refused", sa.ID, id, true, codes.Unauthenticated, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := &bindCalls{}
s := &accountServer{server: &server{deps: Deps{PersonalTokens: store, Identities: repo}}}
ctx := context.Background()
if !tt.noPrincipal {
ctx = access.WithPrincipal(ctx, access.Principal{IdentityID: "alice"})
}
expires := time.Now().UTC().Add(30 * 24 * time.Hour).Truncate(time.Second)
_, err := s.BindIdentityPersonalToken(ctx, &pb.BindIdentityPersonalTokenRequest{IdentityId: string(tt.target), Id: tt.tokenID, Name: "ci", ExpiresAt: timestamppb.New(expires)})
if got := status.Code(err); got != tt.wantCode {
t.Fatalf("code=%v want=%v err=%v", got, tt.wantCode, err)
}
if store.bound != tt.wantBound {
t.Fatalf("bound=%v want=%v", store.bound, tt.wantBound)
}
if !tt.wantBound {
return
}
wantSubject := identity.Subject{Issuer: identity.PersonalTokenIssuer, Subject: id}
if store.id != sa.ID || store.name != "ci" || store.subject != wantSubject {
t.Fatalf("bind id=%q name=%q subject=%+v, want %q %q %+v", store.id, store.name, store.subject, sa.ID, "ci", wantSubject)
}
if store.expires == nil || !store.expires.Equal(expires) {
t.Fatalf("expires=%v want %v", store.expires, expires)
}
if store.audit.ActorID != "alice" || store.audit.RequestID != "personal-token:bind:"+id {
t.Fatalf("audit=%+v, want actor alice request personal-token:bind:<id>", store.audit)
}
})
}
}
+5 -1
View File
@@ -58,8 +58,12 @@ func (s *Server) accountIdentity(r *http.Request) (identity.Identity, error) {
func (s *Server) requireAccount(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Any active identity may authenticate: a person, or a service
// account whose bearer token carries a scoped grant. What the
// identity may then do is the policy chain's call, not the
// credential kind's; an inactive identity is refused here.
value, err := s.accountIdentity(r)
if err != nil || value.Kind != identity.KindUser || !value.CanAct() {
if err != nil || !value.CanAct() {
if err == nil {
err = identity.ErrCredentialRejected
}
+144
View File
@@ -2,6 +2,7 @@ package webui
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
@@ -131,6 +132,149 @@ func TestAccountSessionFailureIsClosed(t *testing.T) {
}
}
// TestRequireAccountAdmitsAnyActiveIdentity pins the bearer-token gate: any
// active identity -- a person or a service account -- is admitted and rides
// the context as the acting identity, while an inactive one is refused, so a
// scoped service-account token can use the API without being a user.
func TestRequireAccountAdmitsAnyActiveIdentity(t *testing.T) {
tests := []struct {
name string
value identity.Identity
want int
}{
{"active user", identity.Identity{ID: "u1", Kind: identity.KindUser, DisplayName: "User", Lifecycle: identity.LifecycleActive}, http.StatusOK},
{"active service account", identity.Identity{ID: "sa1", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleActive}, http.StatusOK},
{"active bot", identity.Identity{ID: "b1", Kind: identity.KindBot, DisplayName: "Bot", Lifecycle: identity.LifecycleActive}, http.StatusOK},
{"suspended user", identity.Identity{ID: "u2", Kind: identity.KindUser, DisplayName: "User", Lifecycle: identity.LifecycleSuspended}, http.StatusUnauthorized},
{"retired service account", identity.Identity{ID: "sa2", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleRetired}, http.StatusUnauthorized},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := &Server{
Authenticate: func(context.Context, string) (identity.Identity, error) { return tt.value, nil },
}
var acting identity.IdentityID
handler := srv.requireAccount(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
if value, ok := ActingIdentity(r.Context()); ok {
acting = value.ID
}
}))
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "https://archie.example/api/summary", nil)
req.Header.Set("Authorization", "Bearer archie_pat_test")
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tt.want, rec.Body.String())
}
if tt.want == http.StatusOK && acting != tt.value.ID {
t.Fatalf("acting identity = %q, want %q", acting, tt.value.ID)
}
})
}
}
// identityRepo answers Get for the identities a test names.
type identityRepo struct {
identity.Repository
values map[identity.IdentityID]identity.Identity
}
func (s identityRepo) Get(_ context.Context, id identity.IdentityID) (identity.Identity, error) {
value, ok := s.values[id]
if !ok {
return identity.Identity{}, identity.ErrNotFound
}
return value, nil
}
// identityTokenStore carries both token contracts: the remote caller's view
// (embedded) and the store side, whose BindPersonalToken names an identity.
type identityTokenStore struct {
identity.PersonalTokens
bound bool
id identity.IdentityID
subject identity.Subject
name string
}
func (s *identityTokenStore) BindPersonalToken(_ context.Context, id identity.IdentityID, subject identity.Subject, name string, _ *time.Time, _ identity.Audit) error {
s.bound, s.id, s.subject, s.name = true, id, subject, name
return nil
}
func (s *identityTokenStore) SubjectsOf(context.Context, identity.IdentityID, string) ([]identity.PersonalToken, error) {
return nil, nil
}
func (s *identityTokenStore) UnbindSubject(context.Context, identity.IdentityID, identity.Subject, identity.Audit) error {
return nil
}
func (s *identityTokenStore) PersonalTokenOf(context.Context, identity.Subject) (identity.PersonalToken, error) {
return identity.PersonalToken{}, identity.ErrNotFound
}
func (s *identityTokenStore) TouchPersonalToken(context.Context, identity.Subject, time.Time) error {
return nil
}
// TestIdentityTokenCreate pins the per-identity token route: an active
// service account gets its raw token exactly once and the store binds only
// its hash, while an unknown or inactive identity is refused.
func TestIdentityTokenCreate(t *testing.T) {
active := identity.Identity{ID: "sa1", Kind: identity.KindServiceAccount, DisplayName: "Canary", Lifecycle: identity.LifecycleActive}
suspended := identity.Identity{ID: "sa2", Kind: identity.KindServiceAccount, DisplayName: "Old", Lifecycle: identity.LifecycleSuspended}
tests := []struct {
name, id, body string
want int
}{
{"active service account", "sa1", `{"name":"ci","days":30}`, http.StatusCreated},
{"unknown identity", "nope", `{"name":"ci","days":30}`, http.StatusBadRequest},
{"inactive identity", "sa2", `{"name":"ci","days":30}`, http.StatusConflict},
{"bad name", "sa1", `{"name":" ","days":30}`, http.StatusBadRequest},
{"bad lifetime", "sa1", `{"name":"ci","days":10}`, http.StatusBadRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
store := &identityTokenStore{}
srv := &Server{
Identities: identityRepo{values: map[identity.IdentityID]identity.Identity{active.ID: active, suspended.ID: suspended}},
PersonalTokens: store,
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "https://archie.example/api/identities/"+tt.id+"/tokens", strings.NewReader(tt.body))
req.Header.Set("Content-Type", "application/json")
req.SetPathValue("id", tt.id)
rec := httptest.NewRecorder()
srv.handleIdentityTokenCreate(rec, req)
if rec.Code != tt.want {
t.Fatalf("status=%d want=%d body=%s", rec.Code, tt.want, rec.Body.String())
}
if tt.want != http.StatusCreated {
if store.bound {
t.Fatal("a refused request still bound a token")
}
return
}
var body struct {
ID string `json:"id"`
Token string `json:"token"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("response: %v (%s)", err, rec.Body.String())
}
if !strings.HasPrefix(body.Token, "archie_pat_") || body.ID == "" {
t.Fatalf("response must show the raw token once: %+v", body)
}
if !store.bound || store.id != active.ID || store.name != "ci" {
t.Fatalf("bound = %+v, want id %q name %q", store, active.ID, "ci")
}
if store.subject.Issuer != identity.PersonalTokenIssuer || store.subject.Subject != body.ID {
t.Fatalf("store kept subject %+v, want the token's hash %q under %q", store.subject, body.ID, identity.PersonalTokenIssuer)
}
})
}
}
type unavailableAccounts struct{ identity.Accounts }
func (unavailableAccounts) AccountSetupRequired(context.Context) (bool, error) {
+66
View File
@@ -7,12 +7,25 @@ import (
"errors"
"net/http"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
)
// identityTokenBinder is the one store-side operation the per-identity token
// route needs: binding a token to a NAMED identity. The remote client's
// caller-scoped PersonalTokens view cannot express that, so the store fronts
// it as its own RPC and the Client carries it under this name.
type identityTokenBinder interface {
BindPersonalToken(ctx context.Context, id identity.IdentityID, subject identity.Subject, name string, expiresAt *time.Time, audit identity.Audit) error
}
// The production store client satisfies the route's narrow contract.
var _ identityTokenBinder = (*staterpc.Client)(nil)
type identityRequest struct {
DisplayName string `json:"display_name"`
Kind identity.Kind `json:"kind"`
@@ -81,6 +94,59 @@ func (s *Server) handleIdentityCommand(w http.ResponseWriter, r *http.Request) {
writeJSON(w, value)
}
// handleIdentityTokenCreate issues an API token for one named identity, which
// is how a non-user identity gets its bearer credential: a person's token
// comes from /api/tokens, a service account's from here. The raw token is
// returned exactly once; the store keeps only its hash.
func (s *Server) handleIdentityTokenCreate(w http.ResponseWriter, r *http.Request) {
id := identity.IdentityID(r.PathValue("id"))
if s.Identities == nil {
http.Error(w, "identity store unavailable", http.StatusServiceUnavailable)
return
}
value, err := s.Identities.Get(r.Context(), id)
if errors.Is(err, identity.ErrNotFound) {
http.Error(w, "No such identity.", http.StatusBadRequest)
return
}
if err != nil {
writeIdentityError(w, err)
return
}
if !value.CanAct() {
http.Error(w, "That identity may not act.", http.StatusConflict)
return
}
name, expiresAt, ok := decodeTokenRequest(w, r)
if !ok {
return
}
// The store side of the PersonalTokens contract binds a token to a named
// identity; the remote caller's view only ever names its own principal.
binder, ok := s.PersonalTokens.(identityTokenBinder)
if !ok {
http.Error(w, "identity token binding unavailable", http.StatusServiceUnavailable)
return
}
raw, subject, err := identity.NewPersonalToken()
if err != nil {
http.Error(w, "cannot create token", http.StatusInternalServerError)
return
}
audit, err := webAudit(r.Context())
if err != nil {
http.Error(w, "cannot create request ID", http.StatusInternalServerError)
return
}
if err := binder.BindPersonalToken(r.Context(), id, subject, name, expiresAt, audit); err != nil {
writeIdentityError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusCreated)
writeJSON(w, map[string]string{"id": subject.Subject, "token": raw})
}
// webAudit attributes a dashboard write to the request's own principal: the
// person the dashboard acts as. Only a request with no principal at all falls
// back to the System identity, which is a real identity the repository
+31 -21
View File
@@ -41,27 +41,8 @@ func (s *Server) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Reques
if !s.personalTokensReady(w, r) {
return
}
var body struct {
Name string `json:"name"`
Days int `json:"days"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&body); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
name := strings.TrimSpace(body.Name)
if name == "" || utf8.RuneCountInString(name) > maxTokenNameLength {
http.Error(w, "Name a token in up to 40 characters.", http.StatusBadRequest)
return
}
var expiresAt *time.Time
switch body.Days {
case 0:
case 7, 30, 90:
t := time.Now().UTC().AddDate(0, 0, body.Days)
expiresAt = &t
default:
http.Error(w, "Lifetime is 7, 30 or 90 days, or none.", http.StatusBadRequest)
name, expiresAt, ok := decodeTokenRequest(w, r)
if !ok {
return
}
raw, subject, err := identity.NewPersonalToken()
@@ -78,6 +59,35 @@ func (s *Server) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Reques
writeJSON(w, map[string]string{"id": subject.Subject, "token": raw})
}
// decodeTokenRequest reads a token request's name and lifetime, the shape the
// personal-token route and the per-identity token route share.
func decodeTokenRequest(w http.ResponseWriter, r *http.Request) (string, *time.Time, bool) {
var body struct {
Name string `json:"name"`
Days int `json:"days"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&body); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return "", nil, false
}
name := strings.TrimSpace(body.Name)
if name == "" || utf8.RuneCountInString(name) > maxTokenNameLength {
http.Error(w, "Name a token in up to 40 characters.", http.StatusBadRequest)
return "", nil, false
}
var expiresAt *time.Time
switch body.Days {
case 0:
case 7, 30, 90:
t := time.Now().UTC().AddDate(0, 0, body.Days)
expiresAt = &t
default:
http.Error(w, "Lifetime is 7, 30 or 90 days, or none.", http.StatusBadRequest)
return "", nil, false
}
return name, expiresAt, true
}
func (s *Server) handlePersonalTokenRevoke(w http.ResponseWriter, r *http.Request) {
if !s.personalTokensReady(w, r) {
return
+22 -5
View File
@@ -318,16 +318,17 @@ func routeOverride(r *http.Request, action access.Action, path string) (access.A
return actionManage(action), access.KindPolicy, segmentValue(path, 2), true
case matchPrefix(path, "/api/control-plane/resources"):
return controlPlaneResourceRoute(action, path)
case updateCommandRoute(action, path):
// Triggering or deferring an install changes the update object, not
// a workflow run: the dashboard kind carries the update's policy.
return access.ActionUpdate, access.KindDashboard, "update", true
case matchPrefix(path, "/api/chat"):
return chatRoute(action)
case matchSegment(path, "/api/sources/", "/secret"):
// Rotating a source's secret hands back its value.
return access.ActionReadSecret, access.KindSecret, segmentValue(path, 2), true
case matchPrefix(path, "/api/harness/terminal"):
// Opening the setup terminal updates the binding's secret.
return access.ActionUpdate, access.KindSecret, "", true
case matchPrefix(path, "/api/harness/bindings"):
return access.ActionRead, access.KindSecret, "", true
case matchPrefix(path, "/api/harness/terminal"), matchPrefix(path, "/api/harness/bindings"):
return harnessSecretRoute(path)
case matchPrefix(path, "/api/channels"), matchPrefix(path, "/api/config"),
matchPrefix(path, "/api/logs"), matchPrefix(path, "/api/tokens"):
return dashboardRoute(action, path)
@@ -335,6 +336,15 @@ func routeOverride(r *http.Request, action access.Action, path string) (access.A
return action, "", "", false
}
// harnessSecretRoute maps the harness surfaces, which work with the binding's
// secret: opening the setup terminal updates it, the bindings view reads it.
func harnessSecretRoute(path string) (access.Action, access.ResourceKind, string, bool) {
if matchPrefix(path, "/api/harness/terminal") {
return access.ActionUpdate, access.KindSecret, "", true
}
return access.ActionRead, access.KindSecret, "", true
}
// dashboardRoute maps the dashboard's own routes: channel settings are
// instance administration, while config, logs and a person's own tokens act
// only as that person, needing no more than a dashboard read.
@@ -395,6 +405,13 @@ func orgRouteAction(action access.Action, path string) access.Action {
return access.ActionUpdate
}
// updateCommandRoute reports whether the request is one of the chat update
// commands, which act on the update object rather than running a workflow.
func updateCommandRoute(action access.Action, path string) bool {
return action == access.ActionCreate &&
(path == "/api/chat/update/install" || path == "/api/chat/update/defer")
}
// chatRoute maps a chat request: posting runs a workflow, anything else reads
// the dashboard.
func chatRoute(action access.Action) (access.Action, access.ResourceKind, string, bool) {
+29
View File
@@ -223,6 +223,35 @@ func TestChannelReloadRoute(t *testing.T) {
}
}
// TestChatRouteMapping pins the chat routes' actions: posting a message runs a
// workflow, while triggering or deferring an update changes the update object
// on the dashboard kind, so a scoped grant can carry it without any run right.
func TestChatRouteMapping(t *testing.T) {
tests := []struct {
method, path string
action access.Action
kind access.ResourceKind
id string
}{
{http.MethodPost, "/api/chat/update/install", access.ActionUpdate, access.KindDashboard, "update"},
{http.MethodPost, "/api/chat/update/defer", access.ActionUpdate, access.KindDashboard, "update"},
{http.MethodPost, "/api/chat/message", access.ActionRun, access.KindWorkflow, ""},
{http.MethodPost, "/api/chat/stream", access.ActionRun, access.KindWorkflow, ""},
{http.MethodPost, "/api/chat/cancel", access.ActionRun, access.KindWorkflow, ""},
{http.MethodPost, "/api/chat/answer", access.ActionRun, access.KindWorkflow, ""},
{http.MethodGet, "/api/chat/update", access.ActionRead, access.KindDashboard, ""},
{http.MethodGet, "/api/chat/sessions", access.ActionRead, access.KindDashboard, ""},
}
for _, tt := range tests {
t.Run(tt.method+" "+tt.path, func(t *testing.T) {
action, kind, id := accessRequest(httptest.NewRequestWithContext(t.Context(), tt.method, tt.path, nil))
if action != tt.action || kind != tt.kind || id != tt.id {
t.Fatalf("accessRequest = %q on %q (%q), want %q on %q (%q)", action, kind, id, tt.action, tt.kind, tt.id)
}
})
}
}
func TestPersonalTokensWithoutPerson(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
t.Run(method, func(t *testing.T) {
+1
View File
@@ -409,6 +409,7 @@ func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
mux.HandleFunc("DELETE /api/tokens/{id}", s.handlePersonalTokenRevoke)
mux.HandleFunc("POST /api/identities", instanceOnly(s.handleIdentityCreate))
mux.HandleFunc("POST /api/identities/{id}/{command}", instanceOnly(s.handleIdentityCommand))
mux.HandleFunc("POST /api/identities/{id}/tokens", instanceOnly(s.handleIdentityTokenCreate))
mux.HandleFunc("GET /api/config", instanceOnly(s.handleConfig))
mux.HandleFunc("GET /api/secret-engines", instanceOnly(s.handleSecretEngines))
mux.HandleFunc("POST /api/secret-references/check", instanceOnly(s.handleSecretCheck))
+13
View File
@@ -27,6 +27,12 @@ service AccountService {
rpc AddPersonalToken(AddPersonalTokenRequest) returns (AddPersonalTokenResponse);
rpc ListPersonalTokens(ListPersonalTokensRequest) returns (ListPersonalTokensResponse);
rpc RevokePersonalToken(RevokePersonalTokenRequest) returns (RevokePersonalTokenResponse);
// BindIdentityPersonalToken binds a personal token to a NAMED identity
// instead of the caller's principal, which is how a service account gets
// its bearer credential. Only non-user targets are accepted: a person's
// token comes from AddPersonalToken. The audit actor is the caller's
// principal, never a request field.
rpc BindIdentityPersonalToken(BindIdentityPersonalTokenRequest) returns (BindIdentityPersonalTokenResponse);
}
// PersonalToken identifies a token by the SHA-256 it binds as; the token
@@ -48,6 +54,13 @@ message ListPersonalTokensRequest {}
message ListPersonalTokensResponse { repeated PersonalToken tokens = 1; }
message RevokePersonalTokenRequest { string id = 1; }
message RevokePersonalTokenResponse {}
message BindIdentityPersonalTokenRequest {
string identity_id = 1;
string id = 2;
string name = 3;
google.protobuf.Timestamp expires_at = 4; // unset: never expires
}
message BindIdentityPersonalTokenResponse {}
message AccountSetupRequest {}
message AccountSetupResponse { bool required = 1; }
message RegisterAccountRequest {