|
| 1 | +package controllers |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "strconv" |
| 6 | + |
| 7 | + "github.com/DIMO-Network/fleet-tenancy-api/internal/models" |
| 8 | + "github.com/DIMO-Network/fleet-tenancy-api/internal/service" |
| 9 | + "github.com/DIMO-Network/fleet-tenancy-api/internal/sharing" |
| 10 | + "github.com/ethereum/go-ethereum/common" |
| 11 | + "github.com/gofiber/fiber/v2" |
| 12 | +) |
| 13 | + |
| 14 | +// SharedOperation — POST /v1/tenants/:tenantId/vehicles/:tokenId/shared-ops |
| 15 | +// |
| 16 | +// The typed shared-operations endpoint (docs/plans/06-signer-key-consolidation.md, |
| 17 | +// step 3): one of four named operations, signed with the tenant's signer on |
| 18 | +// the vehicle owner's kernel account. The body carries an operation ENUM and |
| 19 | +// never calldata — a general "sign this" endpoint would be a signing oracle |
| 20 | +// over every kernel account any operator's signer can act for, and the narrow |
| 21 | +// interface cannot be widened later without that cost, so it starts narrow. |
| 22 | +// |
| 23 | +// Returns 202 and a job id, like a share and for the same reason: every op |
| 24 | +// waits on a bundler for longer than an HTTP request should. |
| 25 | +// |
| 26 | +// Unlike ShareVehicle there is no per-member capability check here, and the |
| 27 | +// difference is deliberate rather than an omission. The expected caller is |
| 28 | +// kaufmann's shared-account workers, whose HTTP boundary already gated the |
| 29 | +// human (its access middleware), and which call this from a background job |
| 30 | +// that carries no session — the same BFF split as invitations, where the |
| 31 | +// calling app owns the human check and this service checks the caller tenant's |
| 32 | +// scope. Re-checking a member's capability at this remove would also be an |
| 33 | +// execution-time re-read of a request-time property, which ShareArgs's |
| 34 | +// ActorWallet comment records as the wrong side of that line. What this |
| 35 | +// endpoint enforces itself is everything that must be true NOW: caller scope, |
| 36 | +// entitlement, live ownership and live signer authority. |
| 37 | +func (c *SharingController) SharedOperation(ctx *fiber.Ctx) error { |
| 38 | + tenantID := ctx.Params("tenantId") |
| 39 | + |
| 40 | + tokenID, err := strconv.ParseInt(ctx.Params("tokenId"), 10, 64) |
| 41 | + if err != nil { |
| 42 | + return fiber.NewError(fiber.StatusBadRequest, "tokenId must be a number") |
| 43 | + } |
| 44 | + |
| 45 | + var body models.SharedOpInput |
| 46 | + if err := ctx.BodyParser(&body); err != nil { |
| 47 | + return fiber.NewError(fiber.StatusBadRequest, "invalid request body") |
| 48 | + } |
| 49 | + if err := c.assertScope(ctx, tenantID, "run shared operation"); err != nil { |
| 50 | + return err |
| 51 | + } |
| 52 | + |
| 53 | + args := sharing.SharedOpArgs{ |
| 54 | + TenantID: tenantID, |
| 55 | + TokenID: tokenID, |
| 56 | + Op: sharing.SharedOp(body.Op), |
| 57 | + TargetWallet: body.TargetWallet, |
| 58 | + SyntheticTokenID: body.SyntheticTokenID, |
| 59 | + ActorWallet: body.ActorWallet, |
| 60 | + } |
| 61 | + // Shape first, before any upstream call — the op/field matrix needs |
| 62 | + // nothing to check. The same validation runs again in the worker, which is |
| 63 | + // the last point before calldata is built. |
| 64 | + if err := args.Validate(); err != nil { |
| 65 | + return fiber.NewError(fiber.StatusBadRequest, err.Error()) |
| 66 | + } |
| 67 | + |
| 68 | + // The full authorization chain runs here so the caller gets a synchronous |
| 69 | + // answer, and again in the worker before the irreversible call. Both are |
| 70 | + // necessary: this one is for the caller, that one is for correctness. |
| 71 | + owner, _, err := c.shares.AuthorizeShare(ctx.Context(), tenantID, tokenID) |
| 72 | + if err != nil { |
| 73 | + return c.shareAuthError(ctx, tenantID, tokenID, err) |
| 74 | + } |
| 75 | + |
| 76 | + switch args.Op { |
| 77 | + case sharing.OpTransferVehicle: |
| 78 | + // Only applicable once the owner is known, which is why it is not in |
| 79 | + // Validate: transferring a vehicle to its current owner is a no-op |
| 80 | + // that would read as success. |
| 81 | + if common.HexToAddress(args.TargetWallet) == owner { |
| 82 | + return fiber.NewError(fiber.StatusBadRequest, "the vehicle already belongs to targetWallet") |
| 83 | + } |
| 84 | + case sharing.OpGrantSacd: |
| 85 | + // The grant's target is the tenant's own client id; a tenant without |
| 86 | + // one has nothing to grant to, and finding that out synchronously |
| 87 | + // beats a job that can only fail. The transfer op deliberately skips |
| 88 | + // this check — its chained re-share is best-effort, and a tenant |
| 89 | + // without a client id can still transfer. |
| 90 | + if _, err := c.shares.GranteeClientID(ctx.Context(), tenantID); err != nil { |
| 91 | + return c.granteeClientIDError(ctx, tenantID, err) |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + jobID, err := c.queue.EnqueueSharedOp(ctx.Context(), args) |
| 96 | + if err != nil { |
| 97 | + if errors.Is(err, sharing.ErrQueueUnavailable) { |
| 98 | + return fiber.NewError(fiber.StatusServiceUnavailable, |
| 99 | + "shared operations are not available in this environment") |
| 100 | + } |
| 101 | + c.logger.Err(err).Str("tenant_id", tenantID).Int64("token_id", tokenID). |
| 102 | + Str("op", body.Op).Msg("enqueue shared operation") |
| 103 | + return fiber.NewError(fiber.StatusInternalServerError, "failed to queue the operation") |
| 104 | + } |
| 105 | + |
| 106 | + return ctx.Status(fiber.StatusAccepted).JSON(models.SharedOpResult{JobID: jobID}) |
| 107 | +} |
| 108 | + |
| 109 | +// SharedOperationStatus — GET /v1/tenants/:tenantId/vehicles/:tokenId/shared-ops/status?jobId= |
| 110 | +// |
| 111 | +// Mirrors ShareStatus exactly: same response shape, same tenant scoping, same |
| 112 | +// not-found answer for another tenant's job — plus the same answer for a job |
| 113 | +// of the other kind, so the two polling surfaces stay distinct despite |
| 114 | +// sharing one id sequence. |
| 115 | +func (c *SharingController) SharedOperationStatus(ctx *fiber.Ctx) error { |
| 116 | + tenantID := ctx.Params("tenantId") |
| 117 | + |
| 118 | + jobID, err := strconv.ParseInt(ctx.Query("jobId"), 10, 64) |
| 119 | + if err != nil { |
| 120 | + return fiber.NewError(fiber.StatusBadRequest, "jobId is required and must be a number") |
| 121 | + } |
| 122 | + if err := c.assertScope(ctx, tenantID, "read shared operation status"); err != nil { |
| 123 | + return err |
| 124 | + } |
| 125 | + |
| 126 | + status, err := c.queue.SharedOpStatus(ctx.Context(), tenantID, jobID) |
| 127 | + if err != nil { |
| 128 | + switch { |
| 129 | + case errors.Is(err, sharing.ErrJobNotFound): |
| 130 | + return fiber.NewError(fiber.StatusNotFound, "no such shared-operation job") |
| 131 | + case errors.Is(err, sharing.ErrQueueUnavailable): |
| 132 | + return fiber.NewError(fiber.StatusServiceUnavailable, |
| 133 | + "shared operations are not available in this environment") |
| 134 | + } |
| 135 | + c.logger.Err(err).Str("tenant_id", tenantID).Int64("job_id", jobID). |
| 136 | + Msg("read shared operation status") |
| 137 | + return fiber.NewError(fiber.StatusInternalServerError, "failed to read the operation status") |
| 138 | + } |
| 139 | + return ctx.JSON(status) |
| 140 | +} |
| 141 | + |
| 142 | +// granteeClientIDError maps a failed grantee resolution: a missing credential |
| 143 | +// or client id is the tenant's configuration state (409, an operator can fix |
| 144 | +// it), everything else is upstream (500 — this resolution is a local read). |
| 145 | +func (c *SharingController) granteeClientIDError(ctx *fiber.Ctx, tenantID string, err error) error { |
| 146 | + switch { |
| 147 | + case errors.Is(err, service.ErrNoClientID), errors.Is(err, service.ErrNoCredential): |
| 148 | + return fiber.NewError(fiber.StatusConflict, "this tenant has no DIMO client id to grant to") |
| 149 | + case errors.Is(err, service.ErrTenantNotFound): |
| 150 | + return fiber.NewError(fiber.StatusForbidden, "unknown tenant") |
| 151 | + } |
| 152 | + c.logger.Err(err).Str("tenant_id", tenantID).Msg("resolve grantee client id") |
| 153 | + return fiber.NewError(fiber.StatusInternalServerError, "failed to resolve the tenant's client id") |
| 154 | +} |
0 commit comments