feat(plugins): add source-control extension contracts (#2117)
This commit is contained in:
@@ -249,6 +249,7 @@ func (c *Controller) httpResolveCredentialLease(ctx *gin.Context) {
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Host string `json:"host"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := ctx.ShouldBindJSON(&request); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"code": "github_invalid_request", "error": "invalid payload"})
|
||||
@@ -256,7 +257,7 @@ func (c *Controller) httpResolveCredentialLease(ctx *gin.Context) {
|
||||
}
|
||||
credential, err := c.service.ResolveGitHubCredential(ctx.Request.Context(), BrokerCredentialRequest{
|
||||
Lease: request.Lease, TaskID: request.TaskID, SessionID: request.SessionID,
|
||||
RepositoryID: request.RepositoryID, Owner: request.Owner, Repo: request.Repo, Host: request.Host,
|
||||
RepositoryID: request.RepositoryID, Owner: request.Owner, Repo: request.Repo, Host: request.Host, Path: request.Path,
|
||||
})
|
||||
if err != nil {
|
||||
writeGitHubAuthError(ctx, err)
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/auth/authn"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/db"
|
||||
"github.com/kandev/kandev/internal/gitcredentials"
|
||||
taskmodels "github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/repository/repoerrors"
|
||||
taskservice "github.com/kandev/kandev/internal/task/service"
|
||||
@@ -324,6 +325,53 @@ func TestCredentialBrokerReadinessUsesExactResolveRoute(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
type exactPathCredentialResolver struct{}
|
||||
|
||||
func (exactPathCredentialResolver) Supports(providerID string) bool { return providerID == "bitbucket" }
|
||||
|
||||
func (exactPathCredentialResolver) Binding(context.Context, gitcredentials.Scope) (string, error) {
|
||||
return "generation-1", nil
|
||||
}
|
||||
|
||||
func (exactPathCredentialResolver) Resolve(context.Context, gitcredentials.Scope) (gitcredentials.Credential, error) {
|
||||
return gitcredentials.Credential{Username: "x-token-auth", Password: "fresh-token"}, nil
|
||||
}
|
||||
|
||||
type exactPathCredentialAuthorizer struct{}
|
||||
|
||||
func (exactPathCredentialAuthorizer) AuthorizeGitCredential(context.Context, gitcredentials.Scope) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestCredentialBrokerResolvePreservesExactProviderPath(t *testing.T) {
|
||||
router, controller := setupControllerTest(&stubClient{})
|
||||
broker := gitcredentials.NewBroker(exactPathCredentialResolver{}, exactPathCredentialAuthorizer{})
|
||||
scope := gitcredentials.Scope{
|
||||
ProviderID: "bitbucket", WorkspaceID: "workspace-1", TaskID: "task-1", SessionID: "session-1",
|
||||
RepositoryID: "repository-1", Host: "bitbucket.example", Path: "/context/scm/ENG/widgets",
|
||||
}
|
||||
lease, err := broker.Issue(t.Context(), scope)
|
||||
if err != nil {
|
||||
t.Fatalf("Issue() error = %v", err)
|
||||
}
|
||||
controller.service.SetCredentialBroker(NewCredentialBrokerFromBroker(broker))
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"lease": lease.Token, "task_id": scope.TaskID, "session_id": scope.SessionID,
|
||||
"repository_id": scope.RepositoryID, "owner": "context", "repo": "scm/ENG/widgets",
|
||||
"host": scope.Host, "path": scope.Path,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal() error = %v", err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/github/credentials/resolve", bytes.NewReader(payload))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200: %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHttpDeleteTaskPRDetachesOnlyTheRequestedWorkspaceAssociation(t *testing.T) {
|
||||
router, store := setupControllerStoreTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -2,29 +2,22 @@ package github
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/gitcredentials"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultCredentialLeaseTTL = 12 * time.Hour
|
||||
credentialLeaseBytes = 32
|
||||
maxCredentialLeasesPerWorkspace = 10_000
|
||||
gitHubTokenUsername = "x-access-token"
|
||||
)
|
||||
const gitHubTokenUsername = "x-access-token"
|
||||
|
||||
var (
|
||||
ErrCredentialLeaseInvalid = errors.New("GitHub credential lease is invalid")
|
||||
ErrCredentialLeaseExpired = errors.New("GitHub credential lease is expired")
|
||||
ErrCredentialLeaseRevoked = errors.New("GitHub credential lease was revoked")
|
||||
ErrCredentialLeaseLimit = errors.New("GitHub credential lease limit reached")
|
||||
ErrCredentialScopeDenied = errors.New("GitHub credential scope denied")
|
||||
ErrCredentialLeaseInvalid = gitcredentials.ErrLeaseInvalid
|
||||
ErrCredentialLeaseExpired = gitcredentials.ErrLeaseExpired
|
||||
ErrCredentialLeaseRevoked = gitcredentials.ErrLeaseRevoked
|
||||
ErrCredentialLeaseLimit = gitcredentials.ErrLeaseLimit
|
||||
ErrCredentialScopeDenied = gitcredentials.ErrScopeDenied
|
||||
)
|
||||
|
||||
// BrokerScopeAuthorizer verifies task/workspace/repository ownership. It is
|
||||
@@ -60,6 +53,7 @@ type BrokerCredentialRequest struct {
|
||||
Owner string
|
||||
Repo string
|
||||
Host string
|
||||
Path string
|
||||
}
|
||||
|
||||
type BrokerCredential struct {
|
||||
@@ -69,32 +63,11 @@ type BrokerCredential struct {
|
||||
Principal AuthPrincipal `json:"principal"`
|
||||
}
|
||||
|
||||
type credentialLeaseRecord struct {
|
||||
WorkspaceID string
|
||||
TaskID string
|
||||
SessionID string
|
||||
RepositoryID string
|
||||
Owner string
|
||||
Repo string
|
||||
Host string
|
||||
CredentialGeneration int64
|
||||
AppRegistrationID string
|
||||
AppCredentialGeneration int64
|
||||
TTL time.Duration
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// CredentialBroker exchanges opaque, task-scoped leases for renewable
|
||||
// automation credentials. Only lease hashes and non-secret scope metadata are
|
||||
// retained; raw leases and GitHub tokens are never persisted in the broker.
|
||||
// CredentialBroker is GitHub's compatibility adapter over the generic
|
||||
// broker. GitHub-specific connection and App-generation checks stay in its
|
||||
// resolver; lease mechanics live in internal/gitcredentials.
|
||||
type CredentialBroker struct {
|
||||
connections workspaceConnectionReader
|
||||
resolver *CredentialResolver
|
||||
authorizer BrokerScopeAuthorizer
|
||||
|
||||
mu sync.Mutex
|
||||
leases map[[sha256.Size]byte]credentialLeaseRecord
|
||||
now func() time.Time
|
||||
broker *gitcredentials.Broker
|
||||
}
|
||||
|
||||
func NewCredentialBroker(
|
||||
@@ -102,75 +75,151 @@ func NewCredentialBroker(
|
||||
resolver *CredentialResolver,
|
||||
authorizer BrokerScopeAuthorizer,
|
||||
) *CredentialBroker {
|
||||
return &CredentialBroker{
|
||||
connections: connections,
|
||||
resolver: resolver,
|
||||
authorizer: authorizer,
|
||||
leases: make(map[[sha256.Size]byte]credentialLeaseRecord),
|
||||
now: time.Now,
|
||||
provider := &gitHubCredentialProvider{connections: connections, resolver: resolver}
|
||||
return &CredentialBroker{broker: gitcredentials.NewBroker(provider, gitHubScopeAuthorizer{authorizer: authorizer})}
|
||||
}
|
||||
|
||||
// NewCredentialBrokerFromBroker binds GitHub's existing HTTP controller to a
|
||||
// provider-neutral broker composed by backendapp.
|
||||
func NewCredentialBrokerFromBroker(broker *gitcredentials.Broker) *CredentialBroker {
|
||||
return &CredentialBroker{broker: broker}
|
||||
}
|
||||
|
||||
// GitCredentialResolver exposes GitHub's live connection and generation
|
||||
// checks as one provider-neutral resolver. Returned credentials retain their
|
||||
// GitHub-specific formatting while generic lease state stays outside this pkg.
|
||||
func (s *Service) GitCredentialResolver() gitcredentials.Resolver {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
return &gitHubCredentialProvider{connections: s.store, resolver: s.resolver}
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) Issue(ctx context.Context, req CredentialLeaseRequest) (*CredentialLease, error) {
|
||||
if err := validateCredentialLeaseScope(
|
||||
req.WorkspaceID, req.TaskID, req.SessionID, req.RepositoryID, req.Owner, req.Repo, req.Host,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b == nil || b.connections == nil || b.resolver == nil || b.authorizer == nil {
|
||||
if b == nil || b.broker == nil {
|
||||
return nil, ErrGitHubNotConfigured
|
||||
}
|
||||
if err := b.authorizer.AuthorizeGitHubRepository(
|
||||
ctx, req.WorkspaceID, req.TaskID, req.SessionID, req.RepositoryID, req.Owner, req.Repo,
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrCredentialScopeDenied, err)
|
||||
}
|
||||
connection, appCredentialGeneration, err := b.issueConnection(ctx, req.WorkspaceID)
|
||||
lease, err := b.broker.Issue(ctx, gitcredentials.Scope{
|
||||
ProviderID: githubProviderName, WorkspaceID: req.WorkspaceID, TaskID: req.TaskID, SessionID: req.SessionID,
|
||||
RepositoryID: req.RepositoryID, Host: req.Host, Path: githubCredentialPath(req.Owner, req.Repo), TTL: req.TTL,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ttl := req.TTL
|
||||
if ttl <= 0 || ttl > defaultCredentialLeaseTTL {
|
||||
ttl = defaultCredentialLeaseTTL
|
||||
}
|
||||
raw := make([]byte, credentialLeaseBytes)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return nil, fmt.Errorf("create GitHub credential lease: %w", err)
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
now := b.now()
|
||||
expiresAt := now.UTC().Add(ttl)
|
||||
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.sweepExpiredLocked(now)
|
||||
if len(b.leases) >= maxCredentialLeasesPerWorkspace &&
|
||||
b.workspaceLeaseCountLocked(req.WorkspaceID) >= maxCredentialLeasesPerWorkspace {
|
||||
return nil, fmt.Errorf("%w for workspace %s", ErrCredentialLeaseLimit, req.WorkspaceID)
|
||||
}
|
||||
b.leases[hash] = credentialLeaseRecord{
|
||||
WorkspaceID: req.WorkspaceID,
|
||||
TaskID: req.TaskID,
|
||||
SessionID: req.SessionID,
|
||||
RepositoryID: req.RepositoryID,
|
||||
Owner: strings.ToLower(req.Owner),
|
||||
Repo: strings.ToLower(req.Repo),
|
||||
Host: strings.ToLower(req.Host),
|
||||
CredentialGeneration: connection.CredentialGeneration,
|
||||
AppRegistrationID: connection.AppRegistrationID,
|
||||
AppCredentialGeneration: appCredentialGeneration,
|
||||
TTL: ttl,
|
||||
ExpiresAt: expiresAt,
|
||||
}
|
||||
return &CredentialLease{Token: token, ExpiresAt: expiresAt}, nil
|
||||
return &CredentialLease{Token: lease.Token, ExpiresAt: lease.ExpiresAt}, nil
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) issueConnection(
|
||||
ctx context.Context,
|
||||
workspaceID string,
|
||||
) (*WorkspaceConnection, int64, error) {
|
||||
connection, err := b.connections.GetWorkspaceConnection(ctx, workspaceID)
|
||||
func (b *CredentialBroker) Resolve(ctx context.Context, req BrokerCredentialRequest) (*BrokerCredential, error) {
|
||||
if b == nil || b.broker == nil {
|
||||
return nil, ErrGitHubNotConfigured
|
||||
}
|
||||
path := req.Path
|
||||
if strings.TrimSpace(path) == "" {
|
||||
path = githubCredentialPath(req.Owner, req.Repo)
|
||||
}
|
||||
credential, err := b.broker.Redeem(ctx, gitcredentials.Redemption{
|
||||
Lease: req.Lease, TaskID: req.TaskID, SessionID: req.SessionID, RepositoryID: req.RepositoryID,
|
||||
Host: req.Host, Path: path,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
principal, _ := credential.Metadata.(AuthPrincipal)
|
||||
return &BrokerCredential{
|
||||
Username: credential.Username, Password: credential.Password, ExpiresAt: credential.ExpiresAt, Principal: principal,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) RevokeTask(taskID string) {
|
||||
if b != nil && b.broker != nil {
|
||||
b.broker.RevokeTask(taskID)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) RevokeSession(sessionID string) {
|
||||
if b != nil && b.broker != nil {
|
||||
b.broker.RevokeSession(sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) RevokeWorkspace(workspaceID string) {
|
||||
if b != nil && b.broker != nil {
|
||||
b.broker.RevokeWorkspace(workspaceID)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) ActiveLeaseCount() int {
|
||||
if b == nil || b.broker == nil {
|
||||
return 0
|
||||
}
|
||||
return b.broker.ActiveLeaseCount()
|
||||
}
|
||||
|
||||
type gitHubScopeAuthorizer struct{ authorizer BrokerScopeAuthorizer }
|
||||
|
||||
func (a gitHubScopeAuthorizer) AuthorizeGitCredential(ctx context.Context, scope gitcredentials.Scope) error {
|
||||
if a.authorizer == nil {
|
||||
return ErrGitHubNotConfigured
|
||||
}
|
||||
owner, repo, err := githubOwnerRepo(scope.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return a.authorizer.AuthorizeGitHubRepository(
|
||||
ctx, scope.WorkspaceID, scope.TaskID, scope.SessionID, scope.RepositoryID, owner, repo,
|
||||
)
|
||||
}
|
||||
|
||||
type gitHubCredentialProvider struct {
|
||||
connections workspaceConnectionReader
|
||||
resolver *CredentialResolver
|
||||
}
|
||||
|
||||
func (*gitHubCredentialProvider) Supports(providerID string) bool {
|
||||
return strings.EqualFold(strings.TrimSpace(providerID), githubProviderName)
|
||||
}
|
||||
|
||||
func (p *gitHubCredentialProvider) Binding(ctx context.Context, scope gitcredentials.Scope) (string, error) {
|
||||
if !strings.EqualFold(scope.Host, defaultGitHubHost) {
|
||||
return "", fmt.Errorf("%w: unsupported host", ErrCredentialScopeDenied)
|
||||
}
|
||||
connection, appGeneration, err := p.issueConnection(ctx, scope.WorkspaceID)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return githubCredentialBindingFor(connection, appGeneration)
|
||||
}
|
||||
|
||||
func (p *gitHubCredentialProvider) Resolve(ctx context.Context, scope gitcredentials.Scope) (gitcredentials.Credential, error) {
|
||||
if p == nil || p.resolver == nil {
|
||||
return gitcredentials.Credential{}, ErrGitHubNotConfigured
|
||||
}
|
||||
owner, repo, err := githubOwnerRepo(scope.Path)
|
||||
if err != nil {
|
||||
return gitcredentials.Credential{}, err
|
||||
}
|
||||
resolved, err := p.resolver.Resolve(ctx, ResolveCredentialRequest{
|
||||
WorkspaceID: scope.WorkspaceID, Purpose: CredentialPurposeGitTransport, RepoOwner: owner, RepoName: repo,
|
||||
})
|
||||
if err != nil {
|
||||
return gitcredentials.Credential{}, err
|
||||
}
|
||||
if resolved == nil || strings.TrimSpace(resolved.credential) == "" {
|
||||
return gitcredentials.Credential{}, ErrCredentialLeaseRevoked
|
||||
}
|
||||
if resolved.Principal.Kind == AuthPrincipalApp && !resolved.Capabilities[CapabilityGitRead] {
|
||||
return gitcredentials.Credential{}, fmt.Errorf("%w: %s", ErrGitHubCapabilityDenied, CapabilityGitRead)
|
||||
}
|
||||
return gitcredentials.Credential{
|
||||
Username: gitHubTokenUsername, Password: resolved.credential, ExpiresAt: resolved.ExpiresAt, Metadata: resolved.Principal,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *gitHubCredentialProvider) issueConnection(ctx context.Context, workspaceID string) (*WorkspaceConnection, int64, error) {
|
||||
if p == nil || p.connections == nil || p.resolver == nil {
|
||||
return nil, 0, ErrGitHubNotConfigured
|
||||
}
|
||||
connection, err := p.connections.GetWorkspaceConnection(ctx, workspaceID)
|
||||
if err != nil {
|
||||
return nil, 0, fmt.Errorf("load GitHub workspace connection: %w", err)
|
||||
}
|
||||
@@ -186,226 +235,42 @@ func (b *CredentialBroker) issueConnection(
|
||||
if strings.TrimSpace(connection.AppRegistrationID) == "" {
|
||||
return nil, 0, ErrGitHubNotConfigured
|
||||
}
|
||||
generation, err := b.resolver.appCredentialGeneration(connection.AppRegistrationID)
|
||||
generation, err := p.resolver.appCredentialGeneration(connection.AppRegistrationID)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return connection, generation, nil
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) Resolve(
|
||||
ctx context.Context,
|
||||
req BrokerCredentialRequest,
|
||||
) (*BrokerCredential, error) {
|
||||
if b == nil || b.connections == nil || b.resolver == nil || b.authorizer == nil {
|
||||
return nil, ErrGitHubNotConfigured
|
||||
}
|
||||
if strings.TrimSpace(req.Lease) == "" {
|
||||
return nil, ErrCredentialLeaseInvalid
|
||||
}
|
||||
record, err := b.loadLease(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := b.authorizeLease(ctx, record); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
credential, err := b.resolveLeaseCredential(ctx, record)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := b.validateLeaseConnection(ctx, record); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !b.renewLease(req.Lease) {
|
||||
return nil, ErrCredentialLeaseRevoked
|
||||
}
|
||||
return credential, nil
|
||||
type githubCredentialBinding struct {
|
||||
CredentialGeneration int64 `json:"credential_generation"`
|
||||
AppRegistrationID string `json:"app_registration_id"`
|
||||
AppCredentialGeneration int64 `json:"app_credential_generation"`
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) loadLease(req BrokerCredentialRequest) (credentialLeaseRecord, error) {
|
||||
hash := sha256.Sum256([]byte(req.Lease))
|
||||
now := b.now()
|
||||
b.mu.Lock()
|
||||
record, ok := b.leases[hash]
|
||||
b.sweepExpiredLocked(now)
|
||||
b.mu.Unlock()
|
||||
if !ok {
|
||||
return credentialLeaseRecord{}, ErrCredentialLeaseInvalid
|
||||
func githubCredentialBindingFor(connection *WorkspaceConnection, appGeneration int64) (string, error) {
|
||||
if connection == nil {
|
||||
return "", ErrGitHubNotConfigured
|
||||
}
|
||||
if !record.ExpiresAt.After(now) {
|
||||
return credentialLeaseRecord{}, ErrCredentialLeaseExpired
|
||||
}
|
||||
if !credentialLeaseMatches(record, req) {
|
||||
return credentialLeaseRecord{}, ErrCredentialScopeDenied
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) authorizeLease(ctx context.Context, record credentialLeaseRecord) error {
|
||||
if err := b.authorizer.AuthorizeGitHubRepository(
|
||||
ctx, record.WorkspaceID, record.TaskID, record.SessionID,
|
||||
record.RepositoryID, record.Owner, record.Repo,
|
||||
); err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrCredentialScopeDenied, err)
|
||||
}
|
||||
return b.validateLeaseConnection(ctx, record)
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) validateLeaseConnection(
|
||||
ctx context.Context,
|
||||
record credentialLeaseRecord,
|
||||
) error {
|
||||
connection, err := b.connections.GetWorkspaceConnection(ctx, record.WorkspaceID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load GitHub workspace connection: %w", err)
|
||||
}
|
||||
if connection == nil || connection.Status != ConnectionStatusActive ||
|
||||
connection.CredentialGeneration != record.CredentialGeneration ||
|
||||
connection.AppRegistrationID != record.AppRegistrationID {
|
||||
return ErrCredentialLeaseRevoked
|
||||
}
|
||||
if record.AppRegistrationID != "" {
|
||||
generation, generationErr := b.resolver.appCredentialGeneration(record.AppRegistrationID)
|
||||
if generationErr != nil || generation != record.AppCredentialGeneration {
|
||||
return ErrCredentialLeaseRevoked
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) resolveLeaseCredential(
|
||||
ctx context.Context,
|
||||
record credentialLeaseRecord,
|
||||
) (*BrokerCredential, error) {
|
||||
resolved, err := b.resolver.Resolve(ctx, ResolveCredentialRequest{
|
||||
WorkspaceID: record.WorkspaceID,
|
||||
Purpose: CredentialPurposeGitTransport,
|
||||
RepoOwner: record.Owner,
|
||||
RepoName: record.Repo,
|
||||
encoded, err := json.Marshal(githubCredentialBinding{
|
||||
CredentialGeneration: connection.CredentialGeneration, AppRegistrationID: connection.AppRegistrationID,
|
||||
AppCredentialGeneration: appGeneration,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return "", fmt.Errorf("encode GitHub credential binding: %w", err)
|
||||
}
|
||||
if resolved.CredentialGeneration != record.CredentialGeneration ||
|
||||
resolved.AppRegistrationID != record.AppRegistrationID ||
|
||||
resolved.AppCredentialGeneration != record.AppCredentialGeneration || resolved.credential == "" {
|
||||
return nil, ErrCredentialLeaseRevoked
|
||||
}
|
||||
// Credential-helper get requests do not distinguish fetch from push. Read
|
||||
// is the minimum transport capability; GitHub enforces write permission if
|
||||
// the returned installation token is subsequently used for a push.
|
||||
if resolved.Principal.Kind == AuthPrincipalApp && !resolved.Capabilities[CapabilityGitRead] {
|
||||
return nil, fmt.Errorf("%w: %s", ErrGitHubCapabilityDenied, CapabilityGitRead)
|
||||
}
|
||||
return &BrokerCredential{
|
||||
Username: gitHubTokenUsername,
|
||||
Password: resolved.credential,
|
||||
ExpiresAt: resolved.ExpiresAt,
|
||||
Principal: resolved.Principal,
|
||||
}, nil
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) renewLease(rawLease string) bool {
|
||||
hash := sha256.Sum256([]byte(rawLease))
|
||||
now := b.now()
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
record, ok := b.leases[hash]
|
||||
if !ok || !record.ExpiresAt.After(now) {
|
||||
return false
|
||||
}
|
||||
ttl := record.TTL
|
||||
if ttl <= 0 || ttl > defaultCredentialLeaseTTL {
|
||||
ttl = defaultCredentialLeaseTTL
|
||||
}
|
||||
record.ExpiresAt = now.UTC().Add(ttl)
|
||||
b.leases[hash] = record
|
||||
return true
|
||||
func githubCredentialPath(owner, repo string) string {
|
||||
return "/" + strings.Trim(strings.TrimSpace(owner), "/") + "/" + strings.Trim(strings.TrimSpace(repo), "/") + ".git"
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) sweepExpiredLocked(now time.Time) {
|
||||
for hash, record := range b.leases {
|
||||
if !record.ExpiresAt.After(now) {
|
||||
delete(b.leases, hash)
|
||||
}
|
||||
func githubOwnerRepo(path string) (string, string, error) {
|
||||
trimmed := strings.TrimSuffix(strings.Trim(path, "/"), ".git")
|
||||
owner, repo, found := strings.Cut(trimmed, "/")
|
||||
if !found || owner == "" || repo == "" || strings.Contains(repo, "/") {
|
||||
return "", "", fmt.Errorf("%w: GitHub repository path is invalid", ErrCredentialScopeDenied)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) workspaceLeaseCountLocked(workspaceID string) int {
|
||||
count := 0
|
||||
for _, record := range b.leases {
|
||||
if record.WorkspaceID == workspaceID {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) RevokeTask(taskID string) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
for hash, record := range b.leases {
|
||||
if record.TaskID == taskID {
|
||||
delete(b.leases, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) RevokeSession(sessionID string) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
for hash, record := range b.leases {
|
||||
if record.SessionID == sessionID {
|
||||
delete(b.leases, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (b *CredentialBroker) RevokeWorkspace(workspaceID string) {
|
||||
if b == nil {
|
||||
return
|
||||
}
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
for hash, record := range b.leases {
|
||||
if record.WorkspaceID == workspaceID {
|
||||
delete(b.leases, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func validateCredentialLeaseScope(workspaceID, taskID, sessionID, repositoryID, owner, repo, host string) error {
|
||||
for name, value := range map[string]string{
|
||||
"workspace": workspaceID,
|
||||
"task": taskID,
|
||||
"session": sessionID,
|
||||
"repository": repositoryID,
|
||||
"owner": owner,
|
||||
"repo": repo,
|
||||
"host": host,
|
||||
} {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return fmt.Errorf("%w: %s is required", ErrCredentialLeaseInvalid, name)
|
||||
}
|
||||
}
|
||||
if !strings.EqualFold(host, defaultGitHubHost) {
|
||||
return fmt.Errorf("%w: unsupported host", ErrCredentialScopeDenied)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func credentialLeaseMatches(record credentialLeaseRecord, req BrokerCredentialRequest) bool {
|
||||
return record.TaskID == req.TaskID &&
|
||||
record.SessionID == req.SessionID &&
|
||||
record.RepositoryID == req.RepositoryID &&
|
||||
strings.EqualFold(record.Owner, req.Owner) &&
|
||||
strings.EqualFold(record.Repo, req.Repo) &&
|
||||
strings.EqualFold(record.Host, req.Host)
|
||||
return owner, repo, nil
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fakeBrokerAuthorizer struct {
|
||||
@@ -118,10 +117,8 @@ func TestCredentialBrokerStoresHashAndRenewsCredentialOnRedemption(t *testing.T)
|
||||
if lease.Token == "" {
|
||||
t.Fatal("empty lease")
|
||||
}
|
||||
for _, record := range broker.leases {
|
||||
if record.TaskID != "task-1" {
|
||||
t.Fatalf("record = %+v", record)
|
||||
}
|
||||
if broker.ActiveLeaseCount() != 1 {
|
||||
t.Fatalf("active leases = %d, want 1", broker.ActiveLeaseCount())
|
||||
}
|
||||
credential, err := broker.Resolve(context.Background(), brokerCredentialRequest(lease.Token))
|
||||
if err != nil {
|
||||
@@ -138,69 +135,6 @@ func TestCredentialBrokerStoresHashAndRenewsCredentialOnRedemption(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialBrokerClampsRequestedLeaseTTL(t *testing.T) {
|
||||
broker, _, _ := newPATCredentialBroker(t)
|
||||
now := time.Now().UTC()
|
||||
broker.now = func() time.Time { return now }
|
||||
req := brokerLeaseRequest()
|
||||
req.TTL = 30 * 24 * time.Hour
|
||||
|
||||
lease, err := broker.Issue(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := now.Add(defaultCredentialLeaseTTL); !lease.ExpiresAt.Equal(want) {
|
||||
t.Fatalf("ExpiresAt = %v, want capped expiry %v", lease.ExpiresAt, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialBrokerRenewsLeaseOnSuccessfulRedemption(t *testing.T) {
|
||||
broker, _, _ := newPATCredentialBroker(t)
|
||||
issuedAt := time.Now().UTC()
|
||||
now := issuedAt
|
||||
broker.now = func() time.Time { return now }
|
||||
req := brokerLeaseRequest()
|
||||
req.TTL = time.Minute
|
||||
|
||||
lease, err := broker.Issue(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = issuedAt.Add(30 * time.Second)
|
||||
if _, err := broker.Resolve(context.Background(), brokerCredentialRequest(lease.Token)); err != nil {
|
||||
t.Fatalf("first Resolve: %v", err)
|
||||
}
|
||||
|
||||
// This is after the original expiry, but still inside the renewed window.
|
||||
now = issuedAt.Add(75 * time.Second)
|
||||
if _, err := broker.Resolve(context.Background(), brokerCredentialRequest(lease.Token)); err != nil {
|
||||
t.Fatalf("Resolve after original expiry: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialBrokerSweepsExpiredLeasesWhenIssuing(t *testing.T) {
|
||||
broker, _, _ := newPATCredentialBroker(t)
|
||||
issuedAt := time.Now().UTC()
|
||||
now := issuedAt
|
||||
broker.now = func() time.Time { return now }
|
||||
req := brokerLeaseRequest()
|
||||
req.TTL = time.Minute
|
||||
|
||||
if _, err := broker.Issue(context.Background(), req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now = issuedAt.Add(2 * time.Minute)
|
||||
req.TaskID = "task-2"
|
||||
req.SessionID = "session-2"
|
||||
if _, err := broker.Issue(context.Background(), req); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got := len(broker.leases); got != 1 {
|
||||
t.Fatalf("lease records = %d, want only the active lease", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCredentialBrokerLimitsActiveLeasesPerWorkspace(t *testing.T) {
|
||||
broker, _, _ := newPATCredentialBroker(t)
|
||||
const maxExpectedLeases = 10_000
|
||||
@@ -332,25 +266,11 @@ func TestCredentialBrokerDoesNotReturnCredentialAfterConcurrentAppSwitch(t *test
|
||||
|
||||
func TestCredentialBrokerExpiryAndExplicitRevocation(t *testing.T) {
|
||||
broker, _, _ := newPATCredentialBroker(t)
|
||||
now := time.Now().UTC()
|
||||
broker.now = func() time.Time { return now }
|
||||
req := brokerLeaseRequest()
|
||||
req.TTL = time.Minute
|
||||
lease, err := broker.Issue(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broker.now = func() time.Time { return now.Add(2 * time.Minute) }
|
||||
_, err = broker.Resolve(context.Background(), brokerCredentialRequest(lease.Token))
|
||||
if !errors.Is(err, ErrCredentialLeaseExpired) {
|
||||
t.Fatalf("error = %v, want expired", err)
|
||||
}
|
||||
|
||||
broker.now = func() time.Time { return now }
|
||||
lease, err = broker.Issue(context.Background(), req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broker.RevokeTask("task-1")
|
||||
_, err = broker.Resolve(context.Background(), brokerCredentialRequest(lease.Token))
|
||||
if !errors.Is(err, ErrCredentialLeaseInvalid) {
|
||||
|
||||
@@ -2,9 +2,7 @@ package github
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
@@ -121,7 +119,7 @@ func TestHandleTaskDeletedRevokesCredentialLeases(t *testing.T) {
|
||||
if err := svc.handleTaskDeleted(context.Background(), event); err != nil {
|
||||
t.Fatalf("handleTaskDeleted: %v", err)
|
||||
}
|
||||
if got := len(broker.leases); got != 0 {
|
||||
if got := broker.ActiveLeaseCount(); got != 0 {
|
||||
t.Fatalf("lease records = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
@@ -200,7 +198,7 @@ func TestHandleWorkspaceDeletedRevokesCredentialLeasesWithoutSecretStore(t *test
|
||||
if err := svc.handleWorkspaceDeleted(context.Background(), event); err != nil {
|
||||
t.Fatalf("handleWorkspaceDeleted: %v", err)
|
||||
}
|
||||
if got := len(broker.leases); got != 0 {
|
||||
if got := broker.ActiveLeaseCount(); got != 0 {
|
||||
t.Fatalf("lease records = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
@@ -220,7 +218,7 @@ func TestSubscribeTaskEventsTerminalSessionRevokesCredentialLease(t *testing.T)
|
||||
if err := svc.eventBus.Publish(context.Background(), events.TaskSessionStateChanged, event); err != nil {
|
||||
t.Fatalf("publish: %v", err)
|
||||
}
|
||||
if got := len(broker.leases); got != 0 {
|
||||
if got := broker.ActiveLeaseCount(); got != 0 {
|
||||
t.Fatalf("lease records = %d, want 0", got)
|
||||
}
|
||||
}
|
||||
@@ -265,16 +263,18 @@ func mustCreateWatch(t *testing.T, store *Store, sessionID, taskID string) {
|
||||
}
|
||||
|
||||
func revocationTestBroker(workspaceID, taskID, sessionID string) *CredentialBroker {
|
||||
hash := sha256.Sum256([]byte(workspaceID + taskID + sessionID))
|
||||
return &CredentialBroker{
|
||||
leases: map[[sha256.Size]byte]credentialLeaseRecord{
|
||||
hash: {
|
||||
WorkspaceID: workspaceID,
|
||||
TaskID: taskID,
|
||||
SessionID: sessionID,
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
},
|
||||
},
|
||||
now: time.Now,
|
||||
connection := &WorkspaceConnection{
|
||||
WorkspaceID: workspaceID, Source: ConnectionSourcePAT, Status: ConnectionStatusActive,
|
||||
}
|
||||
connections := &fakeConnectionReader{workspaces: map[string]*WorkspaceConnection{workspaceID: connection}}
|
||||
broker := NewCredentialBroker(connections, NewCredentialResolver(connections, fakeAuthSecrets{
|
||||
WorkspacePATSecretKey(workspaceID): "transient",
|
||||
}), &fakeBrokerAuthorizer{})
|
||||
if _, err := broker.Issue(context.Background(), CredentialLeaseRequest{
|
||||
WorkspaceID: workspaceID, TaskID: taskID, SessionID: sessionID, RepositoryID: "repository-1",
|
||||
Owner: "owner", Repo: "repo", Host: defaultGitHubHost,
|
||||
}); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return broker
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user