Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
282 changes: 194 additions & 88 deletions api/chunk/v1alpha1/api.pb.go

Large diffs are not rendered by default.

22 changes: 21 additions & 1 deletion api/chunk/v1alpha1/api.proto
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,16 @@ service ChunkService {
rpc GetUploadURL(GetUploadURLRequest) returns (GetUploadURLResponse);

rpc GetSupportedMinecraftVersions(GetSupportedMinecraftVersionsRequest) returns (GetSupportedMinecraftVersionsResponse);

// UploadThumbnail uploads the given PNG image. Formats other than PNG are not supported.
//
// Defined error codes:
// - INVALID_ARGUMENT:
// - chunk id is invalid
// - thumbnail image must be PNG
// - thumbnail size must be 512x512 pixels
// - thumbnail size too big
rpc UploadThumbnail(UploadThumbnailRequest) returns (UploadThumbnailResponse);
}

message CreateChunkRequest {
Expand Down Expand Up @@ -211,4 +221,14 @@ message GetSupportedMinecraftVersionsRequest {

message GetSupportedMinecraftVersionsResponse {
repeated string versions = 1;
}
}

message UploadThumbnailRequest {
string chunk_id = 1;

// image is the raw image bytes
bytes image = 2;
}

message UploadThumbnailResponse {
}
38 changes: 38 additions & 0 deletions api/chunk/v1alpha1/api_grpc.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 7 additions & 5 deletions api/user/v1alpha1/api.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 7 additions & 5 deletions api/user/v1alpha1/types.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added cmd/cli/cli
Binary file not shown.
2 changes: 2 additions & 0 deletions cmd/controlplane/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ func main() {
apiTokenIssuer = fs.String("api-token-issuer", "", "issuer to use for api tokens issued by the control plane. this value will also be set as the tokens audience.") //nolint:lll
apiTokenExpiry = fs.Duration("api-token-expiry", 10*time.Minute, "expiry of api tokens issued by the control plane") //nolint:lll
apiTokenSigningKey = fs.String("api-token-signing-key", "", "key used to sign api tokens issued by the control plane") //nolint:lll
thumbnailMaxSizeKB = fs.Int("thumbnail-max-size-kb", 1000, "max size a thumbnail can be in kilobytes") //nolint:lll
)
if err := ff.Parse(fs, os.Args[1:],
ff.WithEnvVarPrefix("CONTROLPLANE"),
Expand Down Expand Up @@ -88,6 +89,7 @@ func main() {
APITokenIssuer: *apiTokenIssuer,
APITokenExpiry: *apiTokenExpiry,
APITokenSigningKey: *apiTokenSigningKey,
ThumbnailMaxSizeKB: *thumbnailMaxSizeKB,
}
ctx = context.Background()
server = controlplane.NewServer(logger, cfg)
Expand Down
81 changes: 71 additions & 10 deletions controlplane/chunk/chunk.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,21 @@
package chunk

import (
"bytes"
"context"
"errors"
"fmt"
"image"
"io"
"unicode/utf8"

"github.com/spacechunks/explorer/controlplane/authz"
"github.com/spacechunks/explorer/controlplane/blob"
"github.com/spacechunks/explorer/controlplane/contextkey"
apierrs "github.com/spacechunks/explorer/controlplane/errors"
"github.com/spacechunks/explorer/controlplane/resource"

_ "image/png"
)

func (s *svc) CreateChunk(ctx context.Context, chunk resource.Chunk) (resource.Chunk, error) {
Expand Down Expand Up @@ -67,16 +73,8 @@ func (s *svc) UpdateChunk(ctx context.Context, new resource.Chunk) (resource.Chu
return resource.Chunk{}, fmt.Errorf("get chunk: %w", err)
}

actorID, ok := ctx.Value(contextkey.ActorID).(string)
if !ok {
return resource.Chunk{}, errors.New("actor_id not found in context")
}

if err := s.access.AccessAuthorized(
ctx,
authz.WithOwnershipRule(actorID, authz.ChunkResourceDef(old.ID)),
); err != nil {
return resource.Chunk{}, fmt.Errorf("access: %w", err)
if err := s.authorized(ctx, old.ID); err != nil {
return resource.Chunk{}, fmt.Errorf("authorize: %w", err)
}

if new.Name != "" {
Expand Down Expand Up @@ -111,6 +109,47 @@ func (s *svc) GetSupportedMinecraftVersions(ctx context.Context) ([]string, erro
return s.repo.SupportedMinecraftVersions(ctx)
}

func (s *svc) UpdateThumbnail(ctx context.Context, chunkID string, imgData []byte) error {
if err := s.authorized(ctx, chunkID); err != nil {
return fmt.Errorf("authorize: %w", err)
}

cfg, _, err := image.DecodeConfig(bytes.NewBuffer(imgData))
if err != nil {
if errors.Is(err, image.ErrFormat) {
return apierrs.ErrInvalidThumbnailFormat
}
return fmt.Errorf("decode config: %w", err)
}

if cfg.Width != 512 && cfg.Height != 512 {
return apierrs.ErrInvalidThumbnailDimensions
}

if len(imgData)/1000 > s.cfg.ThumbnailMaxSizeKB {
return apierrs.ErrInvalidThumbnailSize
}

obj := blob.Object{
Data: nopReadSeekCloser{bytes.NewReader(imgData)},
}

h, err := obj.Hash()
if err != nil {
return fmt.Errorf("hash: %w", err)
}

if err := s.repo.UpdateThumbnail(ctx, chunkID, h); err != nil {
return fmt.Errorf("db: %w", err)
}

if err := s.s3Store.Put(ctx, blob.CASKeyPrefix, []blob.Object{obj}); err != nil {
return fmt.Errorf("put image: %w", err)
}

return nil
}

func validateChunkFields(chunk resource.Chunk) error {
// FIXME:
// - remove hardcoded limits for tags
Expand All @@ -129,3 +168,25 @@ func validateChunkFields(chunk resource.Chunk) error {

return nil
}

func (s *svc) authorized(ctx context.Context, chunkID string) error {
actorID, ok := ctx.Value(contextkey.ActorID).(string)
if !ok {
return errors.New("actor_id not found in context")
}

if err := s.access.AccessAuthorized(
ctx,
authz.WithOwnershipRule(actorID, authz.ChunkResourceDef(chunkID)),
); err != nil {
return fmt.Errorf("access: %w", err)
}

return nil
}

type nopReadSeekCloser struct {
io.ReadSeeker
}

func (nopReadSeekCloser) Close() error { return nil }
20 changes: 18 additions & 2 deletions controlplane/chunk/flavor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ package chunk_test

import (
"context"
"log/slog"
"os"
"testing"

"github.com/spacechunks/explorer/controlplane/chunk"
Expand Down Expand Up @@ -88,7 +90,14 @@ func TestCreateFlavor(t *testing.T) {
ctx = context.Background()
mockRepo = mock.NewMockChunkRepository(t)
mockAccess = mock.NewMockAuthzAccessEvaluator(t)
svc = chunk.NewService(mockRepo, nil, nil, mockAccess, chunk.Config{})
svc = chunk.NewService(
slog.New(slog.NewTextHandler(os.Stdout, nil)),
mockRepo,
nil,
nil,
mockAccess,
chunk.Config{},
)
)

ctx = context.WithValue(ctx, contextkey.ActorID, "blabla")
Expand Down Expand Up @@ -299,7 +308,14 @@ func TestCreateFlavorVersion(t *testing.T) {
ctx = context.Background()
mockAccess = mock.NewMockAuthzAccessEvaluator(t)
mockRepo = mock.NewMockChunkRepository(t)
svc = chunk.NewService(mockRepo, nil, nil, mockAccess, chunk.Config{})
svc = chunk.NewService(
slog.New(slog.NewTextHandler(os.Stdout, nil)),
mockRepo,
nil,
nil,
mockAccess,
chunk.Config{},
)
)

ctx = context.WithValue(ctx, contextkey.ActorID, "blabla")
Expand Down
1 change: 1 addition & 0 deletions controlplane/chunk/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,5 @@ type Repository interface {
UpdateFlavorVersionPresignedURLData(ctx context.Context, flavorVersionID string, date time.Time, url string) error
SupportedMinecraftVersions(ctx context.Context) ([]string, error)
MinecraftVersionExists(context.Context, string) (bool, error)
UpdateThumbnail(ctx context.Context, chunkID string, imgHash string) error
}
14 changes: 14 additions & 0 deletions controlplane/chunk/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,17 @@ func (s *Server) GetSupportedMinecraftVersions(
Versions: versions,
}, nil
}

func (s *Server) UploadThumbnail(
ctx context.Context,
req *chunkv1alpha1.UploadThumbnailRequest,
) (*chunkv1alpha1.UploadThumbnailResponse, error) {
if _, err := uuid.Parse(req.ChunkId); err != nil {
return nil, apierrs.ErrInvalidChunkID
}

if err := s.service.UpdateThumbnail(ctx, req.ChunkId, req.Image); err != nil {
return nil, err
}
return &chunkv1alpha1.UploadThumbnailResponse{}, nil
}
6 changes: 6 additions & 0 deletions controlplane/chunk/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package chunk

import (
"context"
"log/slog"
"time"

"github.com/spacechunks/explorer/controlplane/authz"
Expand All @@ -42,16 +43,19 @@ type Service interface {
BuildFlavorVersion(ctx context.Context, versionID string) error
GetUploadURL(ctx context.Context, flavorVersionID string, tarballHash string) (string, error)
GetSupportedMinecraftVersions(ctx context.Context) ([]string, error)
UpdateThumbnail(ctx context.Context, chunkID string, imageData []byte) error
}

type Config struct {
Registry string
BaseImage string
Bucket string
PresignedURLExpiry time.Duration
ThumbnailMaxSizeKB int
}

type svc struct {
logger *slog.Logger
repo Repository
jobClient job.Client
s3Store blob.S3Store
Expand All @@ -60,13 +64,15 @@ type svc struct {
}

func NewService(
logger *slog.Logger,
repo Repository,
jobClient job.Client,
s3Store blob.S3Store,
access authz.AccessEvaluator,
cfg Config,
) Service {
return &svc{
logger: logger,
repo: repo,
jobClient: jobClient,
s3Store: s3Store,
Expand Down
Loading