From 9d4e18e09142a694d5025b73ac98bf33a111a456 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 30 Sep 2026 07:52:13 +1000 Subject: [PATCH] feat(egress): capture the OAuth scope set and carry it to the harness secret A Kit's credentialFile cannot render {{.Scopes}} because nothing records the granted scopes: the token response's `scope` field (RFC 6749 section 5.1, space-delimited) was never read, and the token set had nowhere to hold it. capture now parses `scope` into []string and keeps the previous set when the field is absent or empty -- the same rule the refresh token follows, so a refresh that does not repeat the scopes preserves what the login captured. The set is carried end to end: Scopes on harnesssecret.Secret, in harnessSecretPayload (JSON inside the existing encrypted envelope, so no migration), on message HarnessSecret as `repeated string scopes = 8`, and both ways through staterpc values.go. The proto field is load-bearing: the daemon reads the token set over gRPC, so a local-struct-only field is silently lost in production -- TestHarnessSecretConformance proves the round trip in both its local and grpc modes. --- internal/contracts/state/v1/state.pb.go | 13 +++- .../domain/harnesssecret/harnesssecret.go | 6 +- internal/infrastructure/egress/oauth.go | 8 ++- .../infrastructure/egress/oauth_scope_test.go | 63 +++++++++++++++++++ internal/infrastructure/egress/oauth_test.go | 7 ++- .../postgres/harness_secrets.go | 3 + .../postgres/harness_secrets_test.go | 5 +- .../staterpc/conformance_test.go | 8 ++- internal/infrastructure/staterpc/values.go | 3 + proto/state/v1/state.proto | 1 + 10 files changed, 109 insertions(+), 8 deletions(-) create mode 100644 internal/infrastructure/egress/oauth_scope_test.go diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index 2ccaabb70..a6adc5d91 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -4040,6 +4040,7 @@ type HarnessSecret struct { TokenType string `protobuf:"bytes,5,opt,name=token_type,json=tokenType,proto3" json:"token_type,omitempty"` ExpiresAt *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` + Scopes []string `protobuf:"bytes,8,rep,name=scopes,proto3" json:"scopes,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -4123,6 +4124,13 @@ func (x *HarnessSecret) GetUpdatedAt() *timestamppb.Timestamp { return nil } +func (x *HarnessSecret) GetScopes() []string { + if x != nil { + return x.Scopes + } + return nil +} + type GetHarnessSecretRequest struct { state protoimpl.MessageState `protogen:"open.v1"` Org string `protobuf:"bytes,1,opt,name=org,proto3" json:"org,omitempty"` @@ -12191,7 +12199,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\fexecution_id\x18\x01 \x01(\x03R\vexecutionId\x12\x18\n" + "\aattempt\x18\x02 \x01(\x03R\aattempt\"B\n" + "\x11ListStepsResponse\x12-\n" + - "\x05steps\x18\x01 \x03(\v2\x17.state.v1.StepExecutionR\x05steps\"\x98\x02\n" + + "\x05steps\x18\x01 \x03(\v2\x17.state.v1.StepExecutionR\x05steps\"\xb0\x02\n" + "\rHarnessSecret\x12\x10\n" + "\x03org\x18\x01 \x01(\tR\x03org\x12\x18\n" + "\aservice\x18\x02 \x01(\tR\aservice\x12!\n" + @@ -12202,7 +12210,8 @@ const file_state_v1_state_proto_rawDesc = "" + "\n" + "expires_at\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\texpiresAt\x129\n" + "\n" + - "updated_at\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"E\n" + + "updated_at\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\x12\x16\n" + + "\x06scopes\x18\b \x03(\tR\x06scopes\"E\n" + "\x17GetHarnessSecretRequest\x12\x10\n" + "\x03org\x18\x01 \x01(\tR\x03org\x12\x18\n" + "\aservice\x18\x02 \x01(\tR\aservice\"K\n" + diff --git a/internal/domain/harnesssecret/harnesssecret.go b/internal/domain/harnesssecret/harnesssecret.go index 39f3ac3f3..96f73ca91 100644 --- a/internal/domain/harnesssecret/harnesssecret.go +++ b/internal/domain/harnesssecret/harnesssecret.go @@ -21,7 +21,11 @@ type Secret struct { RefreshToken string TokenType string ExpiresAt time.Time - UpdatedAt time.Time + // Scopes are the scopes the provider granted, as the token response's + // space-delimited `scope` field reported them (RFC 6749 section 5.1). + // The set is kept across a refresh that does not repeat the field. + Scopes []string + UpdatedAt time.Time } // Validate rejects a Secret with no identity or no access token: the setup diff --git a/internal/infrastructure/egress/oauth.go b/internal/infrastructure/egress/oauth.go index a5bb4fa86..84d67a313 100644 --- a/internal/infrastructure/egress/oauth.go +++ b/internal/infrastructure/egress/oauth.go @@ -242,12 +242,18 @@ func (rule oauthRule) capture(org string, body []byte, previous harnesssecret.Se if err := json.Unmarshal(body, &parsed); err != nil { return harnesssecret.Secret{}, fmt.Errorf("parse token response: %w", err) } - secret := harnesssecret.Secret{Org: org, Service: rule.service, RefreshToken: previous.RefreshToken} + secret := harnesssecret.Secret{Org: org, Service: rule.service, RefreshToken: previous.RefreshToken, Scopes: previous.Scopes} secret.AccessToken, _ = parsed[access].(string) if v, ok := parsed[refresh].(string); ok && v != "" { secret.RefreshToken = v } secret.TokenType, _ = parsed["token_type"].(string) + // A provider may report the granted scopes only on the login exchange, so + // an absent (or empty) scope keeps the set the previous capture held -- + // the same rule the refresh token follows. + if v, ok := parsed["scope"].(string); ok && v != "" { + secret.Scopes = strings.Fields(v) + } if v, ok := parsed[expiresIn].(float64); ok { secret.ExpiresAt = time.Now().Add(time.Duration(v) * time.Second) } diff --git a/internal/infrastructure/egress/oauth_scope_test.go b/internal/infrastructure/egress/oauth_scope_test.go new file mode 100644 index 000000000..aa62c610b --- /dev/null +++ b/internal/infrastructure/egress/oauth_scope_test.go @@ -0,0 +1,63 @@ +package egress + +import ( + "net/http" + "slices" + "testing" + + "github.com/samcharles93/archie-core/internal/domain/harnesssecret" +) + +// The provider's granted scopes are captured with the token set (RFC 6749 +// section 5.1 spells them as one space-delimited string), so a Kit's +// credential file can render them. +func TestOAuthCaptureRecordsScopes(t *testing.T) { + h := newHarness(t) + h.token.response = `{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600,"scope":"user:inference user:profile"}` + _ = h.oauth.PutHarnessSecret(t.Context(), harnesssecret.Secret{ + Org: "org-1", Service: "claude-code", + AccessToken: "old-access", RefreshToken: "real-refresh", + Scopes: []string{"user:inference"}, + }) + s := h.oauthSession(t, true, true) + + status, _ := postToken(t, h, s, "grant_type=refresh_token&refresh_token="+sentinelRefresh) + + if status != http.StatusOK { + t.Fatalf("status = %d, want 200", status) + } + stored, err := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code") + if err != nil { + t.Fatal(err) + } + if want := []string{"user:inference", "user:profile"}; !slices.Equal(stored.Scopes, want) { + t.Fatalf("stored scopes = %v, want the granted set %v", stored.Scopes, want) + } +} + +// A refresh that does not repeat the scope keeps the set the login captured: +// a provider may return scopes only on the initial exchange. +func TestOAuthCaptureKeepsScopesWhenTheResponseOmitsThem(t *testing.T) { + h := newHarness(t) + h.token.response = `{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600}` + want := []string{"user:inference", "user:profile"} + _ = h.oauth.PutHarnessSecret(t.Context(), harnesssecret.Secret{ + Org: "org-1", Service: "claude-code", + AccessToken: "old-access", RefreshToken: "real-refresh", + Scopes: want, + }) + s := h.oauthSession(t, true, true) + + status, _ := postToken(t, h, s, "grant_type=refresh_token&refresh_token="+sentinelRefresh) + + if status != http.StatusOK { + t.Fatalf("status = %d, want 200", status) + } + stored, err := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code") + if err != nil { + t.Fatal(err) + } + if !slices.Equal(stored.Scopes, want) { + t.Fatalf("stored scopes = %v, want the set the login captured %v", stored.Scopes, want) + } +} diff --git a/internal/infrastructure/egress/oauth_test.go b/internal/infrastructure/egress/oauth_test.go index e7a624b77..0e053b693 100644 --- a/internal/infrastructure/egress/oauth_test.go +++ b/internal/infrastructure/egress/oauth_test.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "net/http/httptest" + "slices" "strings" "sync" "testing" @@ -225,7 +226,11 @@ func TestOAuthUngrantedRunNeitherReadsNorWritesTheOrgToken(t *testing.T) { if strings.Contains(sent, "real-refresh") { t.Fatalf("upstream saw the org's refresh token: %q", sent) } - if stored, _ := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code"); stored != seed { + stored, _ := h.oauth.GetHarnessSecret(t.Context(), "org-1", "claude-code") + if stored.Org != seed.Org || stored.Service != seed.Service || + stored.AccessToken != seed.AccessToken || stored.RefreshToken != seed.RefreshToken || + stored.TokenType != seed.TokenType || !stored.ExpiresAt.Equal(seed.ExpiresAt) || + !slices.Equal(stored.Scopes, seed.Scopes) { t.Fatalf("stored = %+v, want it unchanged", stored) } }) diff --git a/internal/infrastructure/postgres/harness_secrets.go b/internal/infrastructure/postgres/harness_secrets.go index f06ab2561..8117fb99b 100644 --- a/internal/infrastructure/postgres/harness_secrets.go +++ b/internal/infrastructure/postgres/harness_secrets.go @@ -24,6 +24,7 @@ type harnessSecretPayload struct { RefreshToken string `json:"refresh_token"` TokenType string `json:"token_type"` ExpiresAt time.Time `json:"expires_at"` + Scopes []string `json:"scopes,omitempty"` } // GetHarnessSecret returns the stored OAuth token set for an org/service @@ -44,6 +45,7 @@ func (s *EDA) GetHarnessSecret(ctx context.Context, org, service string) (harnes Org: row.Org, Service: row.Service, AccessToken: payload.AccessToken, RefreshToken: payload.RefreshToken, TokenType: payload.TokenType, ExpiresAt: payload.ExpiresAt, + Scopes: payload.Scopes, UpdatedAt: row.UpdatedAt, }, nil } @@ -58,6 +60,7 @@ func (s *EDA) PutHarnessSecret(ctx context.Context, secret harnesssecret.Secret) sealed, err := s.sealHarnessSecret(harnessSecretPayload{ AccessToken: secret.AccessToken, RefreshToken: secret.RefreshToken, TokenType: secret.TokenType, ExpiresAt: secret.ExpiresAt, + Scopes: secret.Scopes, }) if err != nil { return err diff --git a/internal/infrastructure/postgres/harness_secrets_test.go b/internal/infrastructure/postgres/harness_secrets_test.go index 642516234..32fcca8f3 100644 --- a/internal/infrastructure/postgres/harness_secrets_test.go +++ b/internal/infrastructure/postgres/harness_secrets_test.go @@ -2,6 +2,7 @@ package postgres import ( "errors" + "slices" "strings" "testing" "time" @@ -35,6 +36,7 @@ func TestHarnessSecretRoundTripEncrypts(t *testing.T) { Org: "org-1", Service: "claude-code", AccessToken: "at-0123456789abcdef", RefreshToken: "rt-0123456789abcdef", TokenType: "Bearer", ExpiresAt: time.Now().Add(time.Hour).UTC().Truncate(time.Second), + Scopes: []string{"user:inference", "user:profile"}, } if err := s.PutHarnessSecret(t.Context(), in); err != nil { t.Fatalf("PutHarnessSecret() error = %v", err) @@ -53,7 +55,8 @@ func TestHarnessSecretRoundTripEncrypts(t *testing.T) { t.Fatalf("GetHarnessSecret() error = %v", err) } if got.AccessToken != in.AccessToken || got.RefreshToken != in.RefreshToken || - got.TokenType != in.TokenType || !got.ExpiresAt.Equal(in.ExpiresAt) { + got.TokenType != in.TokenType || !got.ExpiresAt.Equal(in.ExpiresAt) || + !slices.Equal(got.Scopes, in.Scopes) { t.Fatalf("GetHarnessSecret() = %+v, want %+v", got, in) } } diff --git a/internal/infrastructure/staterpc/conformance_test.go b/internal/infrastructure/staterpc/conformance_test.go index 3ed24ce91..ee9c3070e 100644 --- a/internal/infrastructure/staterpc/conformance_test.go +++ b/internal/infrastructure/staterpc/conformance_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "net" + "slices" "testing" "time" @@ -637,7 +638,7 @@ func TestHarnessSecretConformance(t *testing.T) { if mode == "grpc" { store = remoteEDA(t, pgstore.Open(t), eda) } - secret := harnesssecret.Secret{Org: "org-a", Service: "service", AccessToken: "access", RefreshToken: "refresh", TokenType: "Bearer", ExpiresAt: time.Now().UTC().Truncate(time.Microsecond).Add(time.Hour)} + secret := harnesssecret.Secret{Org: "org-a", Service: "service", AccessToken: "access", RefreshToken: "refresh", TokenType: "Bearer", ExpiresAt: time.Now().UTC().Truncate(time.Microsecond).Add(time.Hour), Scopes: []string{"user:inference", "user:profile"}} for _, token := range []string{"access", "refreshed-access"} { secret.AccessToken = token if err := store.PutHarnessSecret(t.Context(), secret); err != nil { @@ -651,7 +652,10 @@ func TestHarnessSecretConformance(t *testing.T) { t.Fatal("missing store timestamp") } got.UpdatedAt = time.Time{} - if got != secret { + if got.Org != secret.Org || got.Service != secret.Service || + got.AccessToken != secret.AccessToken || got.RefreshToken != secret.RefreshToken || + got.TokenType != secret.TokenType || !got.ExpiresAt.Equal(secret.ExpiresAt) || + !slices.Equal(got.Scopes, secret.Scopes) { t.Fatalf("round trip mismatch: got %+v, want %+v", got, secret) } } diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index 4f4a1e895..c1c53c709 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "slices" "time" "google.golang.org/grpc/codes" @@ -334,6 +335,7 @@ func harnessSecretProto(s harnesssecret.Secret) *pb.HarnessSecret { Org: s.Org, Service: s.Service, AccessToken: s.AccessToken, RefreshToken: s.RefreshToken, TokenType: s.TokenType, ExpiresAt: timestamp(s.ExpiresAt), UpdatedAt: timestamp(s.UpdatedAt), + Scopes: s.Scopes, } } @@ -345,6 +347,7 @@ func harnessSecretValue(s *pb.HarnessSecret) harnesssecret.Secret { Org: s.Org, Service: s.Service, AccessToken: s.AccessToken, RefreshToken: s.RefreshToken, TokenType: s.TokenType, ExpiresAt: timeValue(s.ExpiresAt), UpdatedAt: timeValue(s.UpdatedAt), + Scopes: slices.Clone(s.Scopes), } } diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index 1bfa8430b..e541046ee 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -639,6 +639,7 @@ message HarnessSecret { string token_type = 5; google.protobuf.Timestamp expires_at = 6; google.protobuf.Timestamp updated_at = 7; + repeated string scopes = 8; } message GetHarnessSecretRequest {