Add trust center files

Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
Sacha Al Himdani
2025-10-24 10:04:54 +02:00
parent e53b1239db
commit 1bd6f7c1c9
55 changed files with 9074 additions and 394 deletions

View File

@@ -62,4 +62,5 @@ const (
InvitationEntityType
MembershipEntityType
SlackMessageEntityType
TrustCenterFileEntityType
)

View File

@@ -0,0 +1,21 @@
CREATE TABLE trust_center_files (
id TEXT PRIMARY KEY,
organization_id TEXT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
tenant_id TEXT NOT NULL,
name TEXT NOT NULL,
category TEXT NOT NULL,
file_id TEXT NOT NULL REFERENCES files(id) ON UPDATE CASCADE ON DELETE RESTRICT,
trust_center_visibility trust_center_visibility NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL
);
ALTER TABLE trust_center_document_accesses ADD COLUMN trust_center_file_id TEXT REFERENCES trust_center_files(id) ON UPDATE CASCADE ON DELETE CASCADE;
ALTER TABLE trust_center_document_accesses DROP CONSTRAINT trust_center_document_accesses_check;
ALTER TABLE trust_center_document_accesses ADD CONSTRAINT trust_center_document_accesses_check CHECK (
(document_id IS NOT NULL)::int + (report_id IS NOT NULL)::int + (trust_center_file_id IS NOT NULL)::int = 1
);
ALTER TABLE trust_center_document_accesses ADD CONSTRAINT trust_center_document_accesses_trust_center_file_id_key UNIQUE (trust_center_access_id, trust_center_file_id);

View File

@@ -32,6 +32,7 @@ type (
TrustCenterAccessID gid.GID `db:"trust_center_access_id"`
DocumentID *gid.GID `db:"document_id"`
ReportID *gid.GID `db:"report_id"`
TrustCenterFileID *gid.GID `db:"trust_center_file_id"`
Active bool `db:"active"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
@@ -61,6 +62,7 @@ SELECT
trust_center_access_id,
document_id,
report_id,
trust_center_file_id,
active,
created_at,
updated_at
@@ -105,6 +107,7 @@ SELECT
trust_center_access_id,
document_id,
report_id,
trust_center_file_id,
active,
created_at,
updated_at
@@ -153,6 +156,7 @@ SELECT
trust_center_access_id,
document_id,
report_id,
trust_center_file_id,
active,
created_at,
updated_at
@@ -200,6 +204,7 @@ INSERT INTO trust_center_document_accesses (
trust_center_access_id,
document_id,
report_id,
trust_center_file_id,
active,
created_at,
updated_at
@@ -209,6 +214,7 @@ INSERT INTO trust_center_document_accesses (
@trust_center_access_id,
@document_id,
@report_id,
@trust_center_file_id,
@active,
@created_at,
@updated_at
@@ -221,6 +227,7 @@ INSERT INTO trust_center_document_accesses (
"trust_center_access_id": tcda.TrustCenterAccessID,
"document_id": tcda.DocumentID,
"report_id": tcda.ReportID,
"trust_center_file_id": tcda.TrustCenterFileID,
"active": tcda.Active,
"created_at": tcda.CreatedAt,
"updated_at": tcda.UpdatedAt,
@@ -338,6 +345,7 @@ SELECT
trust_center_access_id,
document_id,
report_id,
trust_center_file_id,
active,
created_at,
updated_at
@@ -384,6 +392,7 @@ SELECT
trust_center_access_id,
document_id,
report_id,
trust_center_file_id,
active,
created_at,
updated_at
@@ -543,12 +552,13 @@ WITH document_access_data AS (
@trust_center_access_id AS trust_center_access_id,
unnest(@document_ids::text[]) AS document_id,
null::text AS report_id,
null::text AS trust_center_file_id,
false AS active,
@created_at::timestamptz AS created_at,
@updated_at::timestamptz AS updated_at
)
INSERT INTO trust_center_document_accesses (
id, tenant_id, trust_center_access_id, document_id, report_id, active, created_at, updated_at
id, tenant_id, trust_center_access_id, document_id, report_id, trust_center_file_id, active, created_at, updated_at
)
SELECT * FROM document_access_data
`
@@ -589,12 +599,13 @@ WITH report_access_data AS (
@trust_center_access_id AS trust_center_access_id,
null::text AS document_id,
unnest(@report_ids::text[]) AS report_id,
null::text AS trust_center_file_id,
false AS active,
@created_at::timestamptz AS created_at,
@updated_at::timestamptz AS updated_at
)
INSERT INTO trust_center_document_accesses (
id, tenant_id, trust_center_access_id, document_id, report_id, active, created_at, updated_at
id, tenant_id, trust_center_access_id, document_id, report_id, trust_center_file_id, active, created_at, updated_at
)
SELECT * FROM report_access_data
`
@@ -614,3 +625,129 @@ SELECT * FROM report_access_data
return nil
}
func (tcda *TrustCenterDocumentAccess) LoadByTrustCenterAccessIDAndTrustCenterFileID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
trustCenterAccessID gid.GID,
trustCenterFileID gid.GID,
) error {
q := `
SELECT
id,
trust_center_access_id,
document_id,
report_id,
trust_center_file_id,
active,
created_at,
updated_at
FROM
trust_center_document_accesses
WHERE
%s
AND trust_center_access_id = @trust_center_access_id
AND trust_center_file_id = @trust_center_file_id
LIMIT 1;
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"trust_center_access_id": trustCenterAccessID,
"trust_center_file_id": trustCenterFileID,
}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query trust center document access: %w", err)
}
access, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[TrustCenterDocumentAccess])
if err != nil {
return fmt.Errorf("cannot collect trust center document access: %w", err)
}
*tcda = access
return nil
}
func ActivateByTrustCenterFileIDs(
ctx context.Context,
conn pg.Conn,
scope Scoper,
trustCenterAccessID gid.GID,
trustCenterFileIDs []gid.GID,
updatedAt time.Time,
) error {
q := `
UPDATE trust_center_document_accesses
SET active = true, updated_at = @updated_at
WHERE
%s
AND trust_center_access_id = @trust_center_access_id
AND trust_center_file_id = ANY(@trust_center_file_ids)
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"trust_center_access_id": trustCenterAccessID,
"trust_center_file_ids": trustCenterFileIDs,
"updated_at": updatedAt,
}
maps.Copy(args, scope.SQLArguments())
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot activate trust center document accesses by trust center file IDs: %w", err)
}
return nil
}
func (tcdas TrustCenterDocumentAccesses) BulkInsertTrustCenterFileAccesses(
ctx context.Context,
conn pg.Conn,
scope Scoper,
trustCenterAccessID gid.GID,
trustCenterFileIDs []gid.GID,
createdAt time.Time,
) error {
q := `
WITH trust_center_file_access_data AS (
SELECT
generate_gid(decode_base64_unpadded(@tenant_id), @trust_center_document_access_entity_type) AS id,
@tenant_id AS tenant_id,
@trust_center_access_id AS trust_center_access_id,
null::text AS document_id,
null::text AS report_id,
unnest(@trust_center_file_ids::text[]) AS trust_center_file_id,
false AS active,
@created_at::timestamptz AS created_at,
@updated_at::timestamptz AS updated_at
)
INSERT INTO trust_center_document_accesses (
id, tenant_id, trust_center_access_id, document_id, report_id, trust_center_file_id, active, created_at, updated_at
)
SELECT * FROM trust_center_file_access_data
`
args := pgx.StrictNamedArgs{
"tenant_id": scope.GetTenantID(),
"trust_center_document_access_entity_type": TrustCenterDocumentAccessEntityType,
"trust_center_access_id": trustCenterAccessID,
"trust_center_file_ids": trustCenterFileIDs,
"created_at": createdAt,
"updated_at": createdAt,
}
if _, err := conn.Exec(ctx, q, args); err != nil {
return fmt.Errorf("cannot bulk insert trust center file accesses: %w", err)
}
return nil
}

View File

@@ -0,0 +1,347 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
import (
"context"
"fmt"
"maps"
"time"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/jackc/pgx/v5"
"go.gearno.de/kit/pg"
)
type (
TrustCenterFile struct {
ID gid.GID `db:"id"`
OrganizationID gid.GID `db:"organization_id"`
Name string `db:"name"`
Category string `db:"category"`
FileID gid.GID `db:"file_id"`
TrustCenterVisibility TrustCenterVisibility `db:"trust_center_visibility"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
TrustCenterFiles []*TrustCenterFile
)
func (t TrustCenterFile) CursorKey(orderBy TrustCenterFileOrderField) page.CursorKey {
switch orderBy {
case TrustCenterFileOrderFieldName:
return page.NewCursorKey(t.ID, t.Name)
case TrustCenterFileOrderFieldCreatedAt:
return page.NewCursorKey(t.ID, t.CreatedAt)
case TrustCenterFileOrderFieldUpdatedAt:
return page.NewCursorKey(t.ID, t.UpdatedAt)
}
panic(fmt.Sprintf("unsupported order by: %s", orderBy))
}
func (t *TrustCenterFile) LoadByID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
trustCenterFileID gid.GID,
) error {
q := `
SELECT
id,
organization_id,
name,
category,
file_id,
trust_center_visibility,
created_at,
updated_at
FROM
trust_center_files
WHERE
%s
AND id = @trust_center_file_id
LIMIT 1;
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"trust_center_file_id": trustCenterFileID}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query trust_center_files: %w", err)
}
file, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[TrustCenterFile])
if err != nil {
return fmt.Errorf("cannot collect trust center file: %w", err)
}
*t = file
return nil
}
func (t TrustCenterFile) Insert(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
INSERT INTO
trust_center_files (
tenant_id,
id,
organization_id,
name,
category,
file_id,
trust_center_visibility,
created_at,
updated_at
)
VALUES (
@tenant_id,
@id,
@organization_id,
@name,
@category,
@file_id,
@trust_center_visibility,
@created_at,
@updated_at
);
`
args := pgx.StrictNamedArgs{
"tenant_id": scope.GetTenantID(),
"id": t.ID,
"organization_id": t.OrganizationID,
"name": t.Name,
"category": t.Category,
"file_id": t.FileID,
"trust_center_visibility": t.TrustCenterVisibility,
"created_at": t.CreatedAt,
"updated_at": t.UpdatedAt,
}
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot insert trust center file: %w", err)
}
return nil
}
func (t *TrustCenterFile) Update(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
UPDATE trust_center_files
SET
name = @name,
category = @category,
trust_center_visibility = @trust_center_visibility,
updated_at = @updated_at
WHERE
%s
AND id = @id
RETURNING
id,
organization_id,
name,
category,
file_id,
trust_center_visibility,
created_at,
updated_at
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"id": t.ID,
"name": t.Name,
"category": t.Category,
"trust_center_visibility": t.TrustCenterVisibility,
"updated_at": t.UpdatedAt,
}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot update trust center file: %w", err)
}
file, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[TrustCenterFile])
if err != nil {
return fmt.Errorf("cannot collect updated trust center file: %w", err)
}
*t = file
return nil
}
func (t *TrustCenterFile) Delete(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
DELETE FROM
trust_center_files
WHERE
%s
AND id = @id
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"id": t.ID}
maps.Copy(args, scope.SQLArguments())
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot delete trust center file: %w", err)
}
return nil
}
func (t *TrustCenterFiles) LoadByOrganizationID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
cursor *page.Cursor[TrustCenterFileOrderField],
) error {
q := `
SELECT
id,
organization_id,
name,
category,
file_id,
trust_center_visibility,
created_at,
updated_at
FROM
trust_center_files
WHERE
%s
AND organization_id = @organization_id
AND %s
`
q = fmt.Sprintf(q, scope.SQLFragment(), cursor.SQLFragment())
args := pgx.StrictNamedArgs{"organization_id": organizationID}
maps.Copy(args, scope.SQLArguments())
maps.Copy(args, cursor.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query trust_center_files: %w", err)
}
files, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[TrustCenterFile])
if err != nil {
return fmt.Errorf("cannot collect trust center files: %w", err)
}
*t = files
return nil
}
func (t *TrustCenterFiles) CountByOrganizationID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
) (int, error) {
q := `
SELECT
COUNT(*)
FROM
trust_center_files
WHERE
%s
AND organization_id = @organization_id
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"organization_id": organizationID}
maps.Copy(args, scope.SQLArguments())
var count int
err := conn.QueryRow(ctx, q, args).Scan(&count)
if err != nil {
return 0, fmt.Errorf("cannot count trust center files: %w", err)
}
return count, nil
}
func (t *TrustCenterFiles) LoadAllByOrganizationID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
) error {
q := `
SELECT
id,
organization_id,
name,
category,
file_id,
trust_center_visibility,
created_at,
updated_at
FROM
trust_center_files
WHERE
%s
AND organization_id = @organization_id
ORDER BY
created_at DESC
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"organization_id": organizationID}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query trust center files: %w", err)
}
files, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[TrustCenterFile])
if err != nil {
return fmt.Errorf("cannot collect trust center files: %w", err)
}
*t = files
return nil
}

View File

@@ -0,0 +1,51 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package coredata
type (
TrustCenterFileOrderField string
)
const (
TrustCenterFileOrderFieldName TrustCenterFileOrderField = "NAME"
TrustCenterFileOrderFieldCreatedAt TrustCenterFileOrderField = "CREATED_AT"
TrustCenterFileOrderFieldUpdatedAt TrustCenterFileOrderField = "UPDATED_AT"
)
func (p TrustCenterFileOrderField) Column() string {
switch p {
case TrustCenterFileOrderFieldName:
return "name"
case TrustCenterFileOrderFieldCreatedAt:
return "created_at"
case TrustCenterFileOrderFieldUpdatedAt:
return "updated_at"
default:
return string(p)
}
}
func (p TrustCenterFileOrderField) String() string {
return string(p)
}
func (p TrustCenterFileOrderField) MarshalText() ([]byte, error) {
return []byte(p.String()), nil
}
func (p *TrustCenterFileOrderField) UnmarshalText(text []byte) error {
*p = TrustCenterFileOrderField(text)
return nil
}

View File

@@ -98,6 +98,7 @@ type (
TrustCenters *TrustCenterService
TrustCenterAccesses *TrustCenterAccessService
TrustCenterReferences *TrustCenterReferenceService
TrustCenterFiles *TrustCenterFileService
Nonconformities *NonconformityService
Obligations *ObligationService
Snapshots *SnapshotService
@@ -208,6 +209,18 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
tenantService.TrustCenters = &TrustCenterService{svc: tenantService}
tenantService.TrustCenterAccesses = &TrustCenterAccessService{svc: tenantService}
tenantService.TrustCenterReferences = &TrustCenterReferenceService{svc: tenantService}
tenantService.TrustCenterFiles = &TrustCenterFileService{
svc: tenantService,
fileValidator: &filevalidation.FileValidator{
MaxFileSize: 10 * 1024 * 1024, // 10MB
AllowedMimeTypes: map[string]bool{
"application/pdf": true,
},
AllowedExtensions: map[string][]string{
".pdf": {"application/pdf"},
},
},
}
tenantService.Nonconformities = &NonconformityService{svc: tenantService}
tenantService.Obligations = &ObligationService{svc: tenantService}
tenantService.Snapshots = &SnapshotService{svc: tenantService}

View File

@@ -41,11 +41,12 @@ type (
}
UpdateTrustCenterAccessRequest struct {
ID gid.GID
Name *string
Active *bool
DocumentIDs []gid.GID
ReportIDs []gid.GID
ID gid.GID
Name *string
Active *bool
DocumentIDs []gid.GID
ReportIDs []gid.GID
TrustCenterFileIDs []gid.GID
}
DeleteTrustCenterAccessRequest struct {
@@ -65,9 +66,12 @@ func (s TrustCenterAccessService) ListForTrustCenterID(
) (*page.Page[*coredata.TrustCenterAccess, coredata.TrustCenterAccessOrderField], error) {
var accesses coredata.TrustCenterAccesses
err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
return accesses.LoadByTrustCenterID(ctx, conn, s.svc.scope, trustCenterID, cursor)
})
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return accesses.LoadByTrustCenterID(ctx, conn, s.svc.scope, trustCenterID, cursor)
},
)
if err != nil {
return nil, err
@@ -83,9 +87,12 @@ func (s TrustCenterAccessService) ListDocumentAccesses(
) (*page.Page[*coredata.TrustCenterDocumentAccess, coredata.TrustCenterDocumentAccessOrderField], error) {
var documentAccesses coredata.TrustCenterDocumentAccesses
err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
return documentAccesses.LoadByTrustCenterAccessID(ctx, conn, s.svc.scope, trustCenterAccessID, cursor)
})
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return documentAccesses.LoadByTrustCenterAccessID(ctx, conn, s.svc.scope, trustCenterAccessID, cursor)
},
)
if err != nil {
return nil, err
@@ -100,9 +107,12 @@ func (s TrustCenterAccessService) Get(
) (*coredata.TrustCenterAccess, error) {
var access coredata.TrustCenterAccess
err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
return access.LoadByID(ctx, conn, s.svc.scope, accessID)
})
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return access.LoadByID(ctx, conn, s.svc.scope, accessID)
},
)
if err != nil {
return nil, err
@@ -117,9 +127,12 @@ func (s TrustCenterAccessService) GetDocumentAccess(
) (*coredata.TrustCenterDocumentAccess, error) {
var documentAccess coredata.TrustCenterDocumentAccess
err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
return documentAccess.LoadByID(ctx, conn, s.svc.scope, documentAccessID)
})
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return documentAccess.LoadByID(ctx, conn, s.svc.scope, documentAccessID)
},
)
if err != nil {
return nil, err
@@ -133,12 +146,15 @@ func (s TrustCenterAccessService) CountDocumentAccesses(
trustCenterAccessID gid.GID,
) (int, error) {
var count int
err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
var documentAccesses coredata.TrustCenterDocumentAccesses
var err error
count, err = documentAccesses.CountByTrustCenterAccessID(ctx, conn, s.svc.scope, trustCenterAccessID)
return err
})
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
var documentAccesses coredata.TrustCenterDocumentAccesses
var err error
count, err = documentAccesses.CountByTrustCenterAccessID(ctx, conn, s.svc.scope, trustCenterAccessID)
return err
},
)
if err != nil {
return 0, err
@@ -161,9 +177,12 @@ func (s TrustCenterAccessService) ValidateToken(
}
access := &coredata.TrustCenterAccess{}
err = s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
return access.LoadByTrustCenterIDAndEmail(ctx, conn, s.svc.scope, token.Data.TrustCenterID, token.Data.Email)
})
err = s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return access.LoadByTrustCenterIDAndEmail(ctx, conn, s.svc.scope, token.Data.TrustCenterID, token.Data.Email)
},
)
if err != nil {
return nil, fmt.Errorf("access not found or revoked: %w", err)
@@ -188,67 +207,85 @@ func (s TrustCenterAccessService) Create(
var access *coredata.TrustCenterAccess
err := s.svc.pg.WithTx(ctx, func(tx pg.Conn) error {
trustCenter := &coredata.TrustCenter{}
if err := trustCenter.LoadByID(ctx, tx, s.svc.scope, req.TrustCenterID); err != nil {
return fmt.Errorf("cannot load trust center: %w", err)
}
organizationID := trustCenter.OrganizationID
documentIDs := []gid.GID{}
reportIDs := []gid.GID{}
var allDocuments coredata.Documents
filter := coredata.NewDocumentTrustCenterFilter()
if err := allDocuments.LoadAllByOrganizationID(ctx, tx, s.svc.scope, organizationID, filter); err != nil {
return fmt.Errorf("cannot list documents: %w", err)
}
for _, doc := range allDocuments {
documentIDs = append(documentIDs, doc.ID)
}
var allAudits coredata.Audits
auditFilter := coredata.NewAuditTrustCenterFilter()
if err := allAudits.LoadAllByOrganizationID(ctx, tx, s.svc.scope, organizationID, auditFilter); err != nil {
return fmt.Errorf("cannot list audits: %w", err)
}
for _, audit := range allAudits {
if audit.ReportID != nil {
reportIDs = append(reportIDs, *audit.ReportID)
err := s.svc.pg.WithTx(
ctx,
func(tx pg.Conn) error {
trustCenter := &coredata.TrustCenter{}
if err := trustCenter.LoadByID(ctx, tx, s.svc.scope, req.TrustCenterID); err != nil {
return fmt.Errorf("cannot load trust center: %w", err)
}
}
organizationID := trustCenter.OrganizationID
access = &coredata.TrustCenterAccess{
ID: gid.New(s.svc.scope.GetTenantID(), coredata.TrustCenterAccessEntityType),
TenantID: s.svc.scope.GetTenantID(),
TrustCenterID: req.TrustCenterID,
Email: req.Email,
Name: req.Name,
Active: false,
HasAcceptedNonDisclosureAgreement: false,
CreatedAt: now,
UpdatedAt: now,
}
documentIDs := []gid.GID{}
reportIDs := []gid.GID{}
trustCenterFileIDs := []gid.GID{}
if err := access.Insert(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot insert trust center access: %w", err)
}
var allDocuments coredata.Documents
filter := coredata.NewDocumentTrustCenterFilter()
var documentAccesses coredata.TrustCenterDocumentAccesses
if err := documentAccesses.BulkInsertDocumentAccesses(ctx, tx, s.svc.scope, access.ID, documentIDs, now); err != nil {
return fmt.Errorf("cannot bulk insert trust center document accesses: %w", err)
}
if err := allDocuments.LoadAllByOrganizationID(ctx, tx, s.svc.scope, organizationID, filter); err != nil {
return fmt.Errorf("cannot list documents: %w", err)
}
if err := documentAccesses.BulkInsertReportAccesses(ctx, tx, s.svc.scope, access.ID, reportIDs, now); err != nil {
return fmt.Errorf("cannot bulk insert trust center report accesses: %w", err)
}
for _, doc := range allDocuments {
documentIDs = append(documentIDs, doc.ID)
}
return nil
})
var allAudits coredata.Audits
auditFilter := coredata.NewAuditTrustCenterFilter()
if err := allAudits.LoadAllByOrganizationID(ctx, tx, s.svc.scope, organizationID, auditFilter); err != nil {
return fmt.Errorf("cannot list audits: %w", err)
}
for _, audit := range allAudits {
if audit.ReportID != nil {
reportIDs = append(reportIDs, *audit.ReportID)
}
}
var allTrustCenterFiles coredata.TrustCenterFiles
if err := allTrustCenterFiles.LoadAllByOrganizationID(ctx, tx, s.svc.scope, organizationID); err != nil {
return fmt.Errorf("cannot list trust center files: %w", err)
}
for _, file := range allTrustCenterFiles {
trustCenterFileIDs = append(trustCenterFileIDs, file.ID)
}
access = &coredata.TrustCenterAccess{
ID: gid.New(s.svc.scope.GetTenantID(), coredata.TrustCenterAccessEntityType),
TenantID: s.svc.scope.GetTenantID(),
TrustCenterID: req.TrustCenterID,
Email: req.Email,
Name: req.Name,
Active: false,
HasAcceptedNonDisclosureAgreement: false,
CreatedAt: now,
UpdatedAt: now,
}
if err := access.Insert(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot insert trust center access: %w", err)
}
var documentAccesses coredata.TrustCenterDocumentAccesses
if err := documentAccesses.BulkInsertDocumentAccesses(ctx, tx, s.svc.scope, access.ID, documentIDs, now); err != nil {
return fmt.Errorf("cannot bulk insert trust center document accesses: %w", err)
}
if err := documentAccesses.BulkInsertReportAccesses(ctx, tx, s.svc.scope, access.ID, reportIDs, now); err != nil {
return fmt.Errorf("cannot bulk insert trust center report accesses: %w", err)
}
if err := documentAccesses.BulkInsertTrustCenterFileAccesses(ctx, tx, s.svc.scope, access.ID, trustCenterFileIDs, now); err != nil {
return fmt.Errorf("cannot bulk insert trust center file accesses: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
@@ -269,52 +306,61 @@ func (s TrustCenterAccessService) Update(
return nil, fmt.Errorf("name is required")
}
err := s.svc.pg.WithTx(ctx, func(tx pg.Conn) error {
access = &coredata.TrustCenterAccess{}
err := s.svc.pg.WithTx(
ctx,
func(tx pg.Conn) error {
access = &coredata.TrustCenterAccess{}
if err := access.LoadByID(ctx, tx, s.svc.scope, req.ID); err != nil {
return fmt.Errorf("cannot load trust center access: %w", err)
}
shouldSendEmail := req.Active != nil && *req.Active && !access.Active
if req.Name != nil {
access.Name = *req.Name
}
if req.Active != nil {
access.Active = *req.Active
}
access.UpdatedAt = now
if err := access.Update(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot update trust center access: %w", err)
}
if req.DocumentIDs != nil || req.ReportIDs != nil {
if err := coredata.DeactivateByTrustCenterAccessID(ctx, tx, s.svc.scope, access.ID, now); err != nil {
return fmt.Errorf("cannot deactivate existing document accesses: %w", err)
if err := access.LoadByID(ctx, tx, s.svc.scope, req.ID); err != nil {
return fmt.Errorf("cannot load trust center access: %w", err)
}
if req.DocumentIDs != nil {
if err := coredata.ActivateByDocumentIDs(ctx, tx, s.svc.scope, access.ID, req.DocumentIDs, now); err != nil {
return fmt.Errorf("cannot activate document accesses: %w", err)
shouldSendEmail := req.Active != nil && *req.Active && !access.Active
if req.Name != nil {
access.Name = *req.Name
}
if req.Active != nil {
access.Active = *req.Active
}
access.UpdatedAt = now
if err := access.Update(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot update trust center access: %w", err)
}
if req.DocumentIDs != nil || req.ReportIDs != nil || req.TrustCenterFileIDs != nil {
if err := coredata.DeactivateByTrustCenterAccessID(ctx, tx, s.svc.scope, access.ID, now); err != nil {
return fmt.Errorf("cannot deactivate existing document accesses: %w", err)
}
if req.DocumentIDs != nil {
if err := coredata.ActivateByDocumentIDs(ctx, tx, s.svc.scope, access.ID, req.DocumentIDs, now); err != nil {
return fmt.Errorf("cannot activate document accesses: %w", err)
}
}
if req.ReportIDs != nil {
if err := coredata.ActivateByReportIDs(ctx, tx, s.svc.scope, access.ID, req.ReportIDs, now); err != nil {
return fmt.Errorf("cannot activate report accesses: %w", err)
}
}
if req.TrustCenterFileIDs != nil {
if err := coredata.ActivateByTrustCenterFileIDs(ctx, tx, s.svc.scope, access.ID, req.TrustCenterFileIDs, now); err != nil {
return fmt.Errorf("cannot activate trust center file accesses: %w", err)
}
}
}
if req.ReportIDs != nil {
if err := coredata.ActivateByReportIDs(ctx, tx, s.svc.scope, access.ID, req.ReportIDs, now); err != nil {
return fmt.Errorf("cannot activate report accesses: %w", err)
if shouldSendEmail {
if err := s.sendAccessEmail(ctx, tx, access); err != nil {
return fmt.Errorf("failed to send access email: %w", err)
}
}
}
if shouldSendEmail {
if err := s.sendAccessEmail(ctx, tx, access); err != nil {
return fmt.Errorf("failed to send access email: %w", err)
}
}
return nil
})
return nil
},
)
if err != nil {
return nil, err
@@ -327,19 +373,22 @@ func (s TrustCenterAccessService) Delete(
ctx context.Context,
req *DeleteTrustCenterAccessRequest,
) error {
err := s.svc.pg.WithTx(ctx, func(tx pg.Conn) error {
access := &coredata.TrustCenterAccess{}
err := s.svc.pg.WithTx(
ctx,
func(tx pg.Conn) error {
access := &coredata.TrustCenterAccess{}
if err := access.LoadByID(ctx, tx, s.svc.scope, req.ID); err != nil {
return fmt.Errorf("cannot load trust center access: %w", err)
}
if err := access.LoadByID(ctx, tx, s.svc.scope, req.ID); err != nil {
return fmt.Errorf("cannot load trust center access: %w", err)
}
if err := access.Delete(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot delete trust center access: %w", err)
}
if err := access.Delete(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot delete trust center access: %w", err)
}
return nil
})
return nil
},
)
return err
}

View File

@@ -0,0 +1,405 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package probo
import (
"bytes"
"context"
"fmt"
"io"
"mime"
"path/filepath"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/filevalidation"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"go.gearno.de/crypto/uuid"
"go.gearno.de/kit/pg"
)
type (
TrustCenterFileService struct {
svc *TenantService
fileValidator *filevalidation.FileValidator
}
CreateTrustCenterFileRequest struct {
OrganizationID gid.GID
Name string
Category string
File File
TrustCenterVisibility coredata.TrustCenterVisibility
}
UpdateTrustCenterFileRequest struct {
ID gid.GID
Name *string
Category *string
TrustCenterVisibility *coredata.TrustCenterVisibility
}
GetTrustCenterFileRequest struct {
ID gid.GID
}
DeleteTrustCenterFileRequest struct {
ID gid.GID
}
)
func (s TrustCenterFileService) ListForOrganizationID(
ctx context.Context,
organizationID gid.GID,
cursor *page.Cursor[coredata.TrustCenterFileOrderField],
) (*page.Page[*coredata.TrustCenterFile, coredata.TrustCenterFileOrderField], error) {
var files coredata.TrustCenterFiles
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
if err := files.LoadByOrganizationID(ctx, conn, s.svc.scope, organizationID, cursor); err != nil {
return fmt.Errorf("cannot load trust center files: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
return page.NewPage(files, cursor), nil
}
func (s TrustCenterFileService) CountForOrganizationID(
ctx context.Context,
organizationID gid.GID,
) (int, error) {
var count int
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
var err error
count, err = (&coredata.TrustCenterFiles{}).CountByOrganizationID(ctx, conn, s.svc.scope, organizationID)
if err != nil {
return fmt.Errorf("cannot count trust center files: %w", err)
}
return nil
})
if err != nil {
return 0, err
}
return count, nil
}
func (s TrustCenterFileService) Get(
ctx context.Context,
req *GetTrustCenterFileRequest,
) (*coredata.TrustCenterFile, error) {
var file *coredata.TrustCenterFile
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
file = &coredata.TrustCenterFile{}
if err := file.LoadByID(ctx, conn, s.svc.scope, req.ID); err != nil {
return fmt.Errorf("cannot load trust center file: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return file, nil
}
func (s TrustCenterFileService) Create(
ctx context.Context,
req *CreateTrustCenterFileRequest,
) (*coredata.TrustCenterFile, error) {
if req.Name == "" {
return nil, fmt.Errorf("name is required")
}
// Validate file
filename := req.File.Filename
contentType := req.File.ContentType
fileSize, err := s.svc.fileManager.GetFileSize(req.File.Content)
if err != nil {
return nil, fmt.Errorf("cannot get file size: %w", err)
}
if err := s.fileValidator.Validate(filename, contentType, fileSize); err != nil {
return nil, err
}
now := time.Now()
trustCenterFileID := gid.New(s.svc.scope.GetTenantID(), coredata.TrustCenterFileEntityType)
var file *coredata.TrustCenterFile
var s3Key string
err = s.svc.pg.WithTx(
ctx,
func(tx pg.Conn) error {
fileID, objectKey, err := s.uploadFile(ctx, tx, req.File, trustCenterFileID, req.OrganizationID, now)
if err != nil {
return fmt.Errorf("cannot upload file: %w", err)
}
s3Key = objectKey
file = &coredata.TrustCenterFile{
ID: trustCenterFileID,
OrganizationID: req.OrganizationID,
Name: req.Name,
Category: req.Category,
FileID: fileID,
TrustCenterVisibility: req.TrustCenterVisibility,
CreatedAt: now,
UpdatedAt: now,
}
if err := file.Insert(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot insert trust center file: %w", err)
}
return nil
},
)
if err != nil {
s.cleanupS3Object(ctx, s3Key)
return nil, err
}
return file, nil
}
func (s TrustCenterFileService) Update(
ctx context.Context,
req *UpdateTrustCenterFileRequest,
) (*coredata.TrustCenterFile, error) {
now := time.Now()
var file *coredata.TrustCenterFile
if req.Name != nil && *req.Name == "" {
return nil, fmt.Errorf("name is required")
}
err := s.svc.pg.WithTx(
ctx,
func(tx pg.Conn) error {
file = &coredata.TrustCenterFile{}
if err := file.LoadByID(ctx, tx, s.svc.scope, req.ID); err != nil {
return fmt.Errorf("cannot load trust center file: %w", err)
}
if req.Name != nil {
file.Name = *req.Name
}
if req.Category != nil {
file.Category = *req.Category
}
if req.TrustCenterVisibility != nil {
file.TrustCenterVisibility = *req.TrustCenterVisibility
}
file.UpdatedAt = now
if err := file.Update(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot update trust center file: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return file, nil
}
func (s TrustCenterFileService) Delete(
ctx context.Context,
req *DeleteTrustCenterFileRequest,
) error {
err := s.svc.pg.WithTx(
ctx,
func(tx pg.Conn) error {
file := &coredata.TrustCenterFile{}
if err := file.LoadByID(ctx, tx, s.svc.scope, req.ID); err != nil {
return fmt.Errorf("cannot load trust center file: %w", err)
}
if err := file.Delete(ctx, tx, s.svc.scope); err != nil {
return fmt.Errorf("cannot delete trust center file: %w", err)
}
return nil
})
return err
}
func (s TrustCenterFileService) GenerateFileURL(
ctx context.Context,
trustCenterFileID gid.GID,
duration time.Duration,
) (string, error) {
var storedFile *coredata.File
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
file := &coredata.TrustCenterFile{}
if err := file.LoadByID(ctx, conn, s.svc.scope, trustCenterFileID); err != nil {
return fmt.Errorf("cannot load trust center file: %w", err)
}
storedFile = &coredata.File{}
if err := storedFile.LoadByID(ctx, conn, s.svc.scope, file.FileID); err != nil {
return fmt.Errorf("cannot load file: %w", err)
}
return nil
},
)
if err != nil {
return "", err
}
fileURL, err := s.svc.fileManager.GenerateFileUrl(ctx, storedFile, duration)
if err != nil {
return "", fmt.Errorf("cannot generate file URL: %w", err)
}
return fileURL, nil
}
func (s TrustCenterFileService) uploadFile(
ctx context.Context,
tx pg.Conn,
file File,
trustCenterFileID gid.GID,
organizationID gid.GID,
now time.Time,
) (gid.GID, string, error) {
fileID := gid.New(s.svc.scope.GetTenantID(), coredata.FileEntityType)
objectKey, err := uuid.NewV7()
if err != nil {
return gid.GID{}, "", fmt.Errorf("cannot generate object key: %w", err)
}
var fileSize int64
var fileContent io.ReadSeeker
filename := file.Filename
contentType := file.ContentType
if readSeeker, ok := file.Content.(io.ReadSeeker); ok {
if file.Size <= 0 {
size, err := readSeeker.Seek(0, io.SeekEnd)
if err != nil {
return gid.GID{}, "", fmt.Errorf("cannot determine file size: %w", err)
}
fileSize = size
_, err = readSeeker.Seek(0, io.SeekStart)
if err != nil {
return gid.GID{}, "", fmt.Errorf("cannot reset file position: %w", err)
}
} else {
fileSize = file.Size
}
fileContent = readSeeker
} else {
buf, err := io.ReadAll(file.Content)
if err != nil {
return gid.GID{}, "", fmt.Errorf("cannot read file: %w", err)
}
fileSize = int64(len(buf))
fileContent = bytes.NewReader(buf)
}
if contentType == "" {
contentType = "application/octet-stream"
if filename != "" {
if detectedType := mime.TypeByExtension(filepath.Ext(filename)); detectedType != "" {
contentType = detectedType
}
}
}
_, err = s.svc.s3.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.svc.bucket),
Key: aws.String(objectKey.String()),
Body: fileContent,
ContentType: aws.String(contentType),
Metadata: map[string]string{
"type": "trust-center-file",
"trust-center-file-id": trustCenterFileID.String(),
"organization-id": organizationID.String(),
},
})
if err != nil {
return gid.GID{}, "", fmt.Errorf("cannot upload file to S3: %w", err)
}
fileRecord := &coredata.File{
ID: fileID,
BucketName: s.svc.bucket,
MimeType: contentType,
FileName: filename,
FileKey: objectKey.String(),
FileSize: fileSize,
CreatedAt: now,
UpdatedAt: now,
}
if err := fileRecord.Insert(ctx, tx, s.svc.scope); err != nil {
return gid.GID{}, "", fmt.Errorf("cannot insert file: %w", err)
}
return fileID, objectKey.String(), nil
}
func (s TrustCenterFileService) cleanupS3Object(ctx context.Context, s3Key string) {
if s3Key == "" {
return
}
s.svc.s3.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(s.svc.bucket),
Key: aws.String(s3Key),
})
}

View File

@@ -1187,6 +1187,24 @@ enum TrustCenterReferenceOrderField
)
}
enum TrustCenterFileOrderField
@goModel(
model: "github.com/getprobo/probo/pkg/coredata.TrustCenterFileOrderField"
) {
NAME
@goEnum(
value: "github.com/getprobo/probo/pkg/coredata.TrustCenterFileOrderFieldName"
)
CREATED_AT
@goEnum(
value: "github.com/getprobo/probo/pkg/coredata.TrustCenterFileOrderFieldCreatedAt"
)
UPDATED_AT
@goEnum(
value: "github.com/getprobo/probo/pkg/coredata.TrustCenterFileOrderFieldUpdatedAt"
)
}
enum SnapshotsType
@goModel(model: "github.com/getprobo/probo/pkg/coredata.SnapshotsType") {
RISKS
@@ -1422,6 +1440,14 @@ input TrustCenterReferenceOrder
field: TrustCenterReferenceOrderField!
}
input TrustCenterFileOrder
@goModel(
model: "github.com/getprobo/probo/pkg/server/api/console/v1/types.TrustCenterFileOrderBy"
) {
direction: OrderDirection!
field: TrustCenterFileOrderField!
}
input EvidenceOrder
@goModel(
model: "github.com/getprobo/probo/pkg/server/api/console/v1/types.EvidenceOrderBy"
@@ -1749,6 +1775,14 @@ type Organization implements Node {
orderBy: SnapshotOrder
): SnapshotConnection! @goField(forceResolver: true)
trustCenterFiles(
first: Int
after: CursorKey
last: Int
before: CursorKey
orderBy: TrustCenterFileOrder
): TrustCenterFileConnection! @goField(forceResolver: true)
trustCenter: TrustCenter @goField(forceResolver: true)
customDomain: CustomDomain @goField(forceResolver: true)
@@ -2391,6 +2425,7 @@ type TrustCenterDocumentAccess implements Node {
trustCenterAccess: TrustCenterAccess! @goField(forceResolver: true)
document: Document @goField(forceResolver: true)
report: Report @goField(forceResolver: true)
trustCenterFile: TrustCenterFile @goField(forceResolver: true)
}
type TrustCenterDocumentAccessConnection
@@ -2441,6 +2476,31 @@ type TrustCenterReferenceEdge {
node: TrustCenterReference!
}
type TrustCenterFile implements Node {
id: ID!
name: String!
category: String!
fileUrl: String! @goField(forceResolver: true)
trustCenterVisibility: TrustCenterVisibility!
createdAt: Datetime!
updatedAt: Datetime!
organization: Organization! @goField(forceResolver: true)
}
type TrustCenterFileConnection
@goModel(
model: "github.com/getprobo/probo/pkg/server/api/console/v1/types.TrustCenterFileConnection"
) {
totalCount: Int! @goField(forceResolver: true)
edges: [TrustCenterFileEdge!]!
pageInfo: PageInfo!
}
type TrustCenterFileEdge {
cursor: CursorKey!
node: TrustCenterFile!
}
type UserConnection
@goModel(
model: "github.com/getprobo/probo/pkg/server/api/console/v1/types.UserConnection"
@@ -2824,6 +2884,23 @@ type Mutation {
input: DeleteTrustCenterReferenceInput!
): DeleteTrustCenterReferencePayload!
# Trust Center File mutations
createTrustCenterFile(
input: CreateTrustCenterFileInput!
): CreateTrustCenterFilePayload!
updateTrustCenterFile(
input: UpdateTrustCenterFileInput!
): UpdateTrustCenterFilePayload!
getTrustCenterFile(
input: GetTrustCenterFileInput!
): GetTrustCenterFilePayload!
deleteTrustCenterFile(
input: DeleteTrustCenterFileInput!
): DeleteTrustCenterFilePayload!
# User mutations
confirmEmail(input: ConfirmEmailInput!): ConfirmEmailPayload!
inviteUser(input: InviteUserInput!): InviteUserPayload!
@@ -3151,6 +3228,7 @@ input UpdateTrustCenterAccessInput {
active: Boolean
documentIds: [ID!]
reportIds: [ID!]
trustCenterFileIds: [ID!]
}
input DeleteTrustCenterAccessInput {
@@ -3177,6 +3255,29 @@ input DeleteTrustCenterReferenceInput {
id: ID!
}
input CreateTrustCenterFileInput {
organizationId: ID!
name: String!
category: String!
file: Upload!
trustCenterVisibility: TrustCenterVisibility!
}
input UpdateTrustCenterFileInput {
id: ID!
name: String
category: String
trustCenterVisibility: TrustCenterVisibility
}
input GetTrustCenterFileInput {
id: ID!
}
input DeleteTrustCenterFileInput {
id: ID!
}
input CreateVendorInput {
organizationId: ID!
name: String!
@@ -3854,6 +3955,22 @@ type DeleteTrustCenterReferencePayload {
deletedTrustCenterReferenceId: ID!
}
type CreateTrustCenterFilePayload {
trustCenterFileEdge: TrustCenterFileEdge!
}
type UpdateTrustCenterFilePayload {
trustCenterFile: TrustCenterFile!
}
type GetTrustCenterFilePayload {
trustCenterFile: TrustCenterFile!
}
type DeleteTrustCenterFilePayload {
deletedTrustCenterFileId: ID!
}
type CreateControlPayload {
controlEdge: ControlEdge!
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,65 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package types
import (
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
)
type TrustCenterFileOrderBy = OrderBy[coredata.TrustCenterFileOrderField]
type TrustCenterFileConnection struct {
TotalCount int `json:"totalCount"`
Edges []*TrustCenterFileEdge `json:"edges"`
PageInfo *PageInfo `json:"pageInfo"`
ParentID gid.GID `json:"-"`
}
func NewTrustCenterFile(tcf *coredata.TrustCenterFile) *TrustCenterFile {
return &TrustCenterFile{
ID: tcf.ID,
Name: tcf.Name,
Category: tcf.Category,
TrustCenterVisibility: tcf.TrustCenterVisibility,
CreatedAt: tcf.CreatedAt,
UpdatedAt: tcf.UpdatedAt,
}
}
func NewTrustCenterFileConnection(
p *page.Page[*coredata.TrustCenterFile, coredata.TrustCenterFileOrderField],
parentID gid.GID,
) *TrustCenterFileConnection {
var edges = make([]*TrustCenterFileEdge, len(p.Data))
for i := range edges {
edges[i] = NewTrustCenterFileEdge(p.Data[i], p.Cursor.OrderBy.Field)
}
return &TrustCenterFileConnection{
Edges: edges,
PageInfo: NewPageInfo(p),
ParentID: parentID,
}
}
func NewTrustCenterFileEdge(tcf *coredata.TrustCenterFile, orderBy coredata.TrustCenterFileOrderField) *TrustCenterFileEdge {
return &TrustCenterFileEdge{
Cursor: tcf.CursorKey(orderBy),
Node: NewTrustCenterFile(tcf),
}
}

View File

@@ -541,6 +541,18 @@ type CreateTrustCenterAccessPayload struct {
TrustCenterAccessEdge *TrustCenterAccessEdge `json:"trustCenterAccessEdge"`
}
type CreateTrustCenterFileInput struct {
OrganizationID gid.GID `json:"organizationId"`
Name string `json:"name"`
Category string `json:"category"`
File graphql.Upload `json:"file"`
TrustCenterVisibility coredata.TrustCenterVisibility `json:"trustCenterVisibility"`
}
type CreateTrustCenterFilePayload struct {
TrustCenterFileEdge *TrustCenterFileEdge `json:"trustCenterFileEdge"`
}
type CreateTrustCenterReferenceInput struct {
TrustCenterID gid.GID `json:"trustCenterId"`
Name string `json:"name"`
@@ -916,6 +928,14 @@ type DeleteTrustCenterAccessPayload struct {
DeletedTrustCenterAccessID gid.GID `json:"deletedTrustCenterAccessId"`
}
type DeleteTrustCenterFileInput struct {
ID gid.GID `json:"id"`
}
type DeleteTrustCenterFilePayload struct {
DeletedTrustCenterFileID gid.GID `json:"deletedTrustCenterFileId"`
}
type DeleteTrustCenterNDAInput struct {
TrustCenterID gid.GID `json:"trustCenterId"`
}
@@ -1170,6 +1190,14 @@ type GenerateFrameworkStateOfApplicabilityPayload struct {
Data string `json:"data"`
}
type GetTrustCenterFileInput struct {
ID gid.GID `json:"id"`
}
type GetTrustCenterFilePayload struct {
TrustCenterFile *TrustCenterFile `json:"trustCenterFile"`
}
type ImportFrameworkInput struct {
OrganizationID gid.GID `json:"organizationId"`
File graphql.Upload `json:"file"`
@@ -1365,6 +1393,7 @@ type Organization struct {
ContinualImprovements *ContinualImprovementConnection `json:"continualImprovements"`
ProcessingActivities *ProcessingActivityConnection `json:"processingActivities"`
Snapshots *SnapshotConnection `json:"snapshots"`
TrustCenterFiles *TrustCenterFileConnection `json:"trustCenterFiles"`
TrustCenter *TrustCenter `json:"trustCenter,omitempty"`
CustomDomain *CustomDomain `json:"customDomain,omitempty"`
CreatedAt time.Time `json:"createdAt"`
@@ -1675,6 +1704,7 @@ type TrustCenterDocumentAccess struct {
TrustCenterAccess *TrustCenterAccess `json:"trustCenterAccess"`
Document *Document `json:"document,omitempty"`
Report *Report `json:"report,omitempty"`
TrustCenterFile *TrustCenterFile `json:"trustCenterFile,omitempty"`
}
func (TrustCenterDocumentAccess) IsNode() {}
@@ -1690,6 +1720,25 @@ type TrustCenterEdge struct {
Node *TrustCenter `json:"node"`
}
type TrustCenterFile struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
Category string `json:"category"`
FileURL string `json:"fileUrl"`
TrustCenterVisibility coredata.TrustCenterVisibility `json:"trustCenterVisibility"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Organization *Organization `json:"organization"`
}
func (TrustCenterFile) IsNode() {}
func (this TrustCenterFile) GetID() gid.GID { return this.ID }
type TrustCenterFileEdge struct {
Cursor page.CursorKey `json:"cursor"`
Node *TrustCenterFile `json:"node"`
}
type TrustCenterReference struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
@@ -1948,17 +1997,29 @@ type UpdateTaskPayload struct {
}
type UpdateTrustCenterAccessInput struct {
ID gid.GID `json:"id"`
Name *string `json:"name,omitempty"`
Active *bool `json:"active,omitempty"`
DocumentIds []gid.GID `json:"documentIds,omitempty"`
ReportIds []gid.GID `json:"reportIds,omitempty"`
ID gid.GID `json:"id"`
Name *string `json:"name,omitempty"`
Active *bool `json:"active,omitempty"`
DocumentIds []gid.GID `json:"documentIds,omitempty"`
ReportIds []gid.GID `json:"reportIds,omitempty"`
TrustCenterFileIds []gid.GID `json:"trustCenterFileIds,omitempty"`
}
type UpdateTrustCenterAccessPayload struct {
TrustCenterAccess *TrustCenterAccess `json:"trustCenterAccess"`
}
type UpdateTrustCenterFileInput struct {
ID gid.GID `json:"id"`
Name *string `json:"name,omitempty"`
Category *string `json:"category,omitempty"`
TrustCenterVisibility *coredata.TrustCenterVisibility `json:"trustCenterVisibility,omitempty"`
}
type UpdateTrustCenterFilePayload struct {
TrustCenterFile *TrustCenterFile `json:"trustCenterFile"`
}
type UpdateTrustCenterInput struct {
TrustCenterID gid.GID `json:"trustCenterId"`
Active *bool `json:"active,omitempty"`

View File

@@ -1288,11 +1288,12 @@ func (r *mutationResolver) UpdateTrustCenterAccess(ctx context.Context, input ty
prb := r.ProboService(ctx, input.ID.TenantID())
access, err := prb.TrustCenterAccesses.Update(ctx, &probo.UpdateTrustCenterAccessRequest{
ID: input.ID,
Name: input.Name,
Active: input.Active,
DocumentIDs: input.DocumentIds,
ReportIDs: input.ReportIds,
ID: input.ID,
Name: input.Name,
Active: input.Active,
DocumentIDs: input.DocumentIds,
ReportIDs: input.ReportIds,
TrustCenterFileIDs: input.TrustCenterFileIds,
})
if err != nil {
panic(fmt.Errorf("cannot update trust center access: %w", err))
@@ -1390,6 +1391,82 @@ func (r *mutationResolver) DeleteTrustCenterReference(ctx context.Context, input
}, nil
}
// CreateTrustCenterFile is the resolver for the createTrustCenterFile field.
func (r *mutationResolver) CreateTrustCenterFile(ctx context.Context, input types.CreateTrustCenterFileInput) (*types.CreateTrustCenterFilePayload, error) {
prb := r.ProboService(ctx, input.OrganizationID.TenantID())
file, err := prb.TrustCenterFiles.Create(ctx, &probo.CreateTrustCenterFileRequest{
OrganizationID: input.OrganizationID,
Name: input.Name,
Category: input.Category,
File: probo.File{
Content: input.File.File,
Filename: input.File.Filename,
Size: input.File.Size,
ContentType: input.File.ContentType,
},
TrustCenterVisibility: input.TrustCenterVisibility,
})
if err != nil {
return nil, fmt.Errorf("cannot create trust center file: %w", err)
}
return &types.CreateTrustCenterFilePayload{
TrustCenterFileEdge: types.NewTrustCenterFileEdge(file, coredata.TrustCenterFileOrderFieldCreatedAt),
}, nil
}
// UpdateTrustCenterFile is the resolver for the updateTrustCenterFile field.
func (r *mutationResolver) UpdateTrustCenterFile(ctx context.Context, input types.UpdateTrustCenterFileInput) (*types.UpdateTrustCenterFilePayload, error) {
prb := r.ProboService(ctx, input.ID.TenantID())
file, err := prb.TrustCenterFiles.Update(ctx, &probo.UpdateTrustCenterFileRequest{
ID: input.ID,
Name: input.Name,
Category: input.Category,
TrustCenterVisibility: input.TrustCenterVisibility,
})
if err != nil {
return nil, fmt.Errorf("cannot update trust center file: %w", err)
}
return &types.UpdateTrustCenterFilePayload{
TrustCenterFile: types.NewTrustCenterFile(file),
}, nil
}
// GetTrustCenterFile is the resolver for the getTrustCenterFile field.
func (r *mutationResolver) GetTrustCenterFile(ctx context.Context, input types.GetTrustCenterFileInput) (*types.GetTrustCenterFilePayload, error) {
prb := r.ProboService(ctx, input.ID.TenantID())
file, err := prb.TrustCenterFiles.Get(ctx, &probo.GetTrustCenterFileRequest{
ID: input.ID,
})
if err != nil {
return nil, fmt.Errorf("cannot get trust center file: %w", err)
}
return &types.GetTrustCenterFilePayload{
TrustCenterFile: types.NewTrustCenterFile(file),
}, nil
}
// DeleteTrustCenterFile is the resolver for the deleteTrustCenterFile field.
func (r *mutationResolver) DeleteTrustCenterFile(ctx context.Context, input types.DeleteTrustCenterFileInput) (*types.DeleteTrustCenterFilePayload, error) {
prb := r.ProboService(ctx, input.ID.TenantID())
err := prb.TrustCenterFiles.Delete(ctx, &probo.DeleteTrustCenterFileRequest{
ID: input.ID,
})
if err != nil {
return nil, fmt.Errorf("cannot delete trust center file: %w", err)
}
return &types.DeleteTrustCenterFilePayload{
DeletedTrustCenterFileID: input.ID,
}, nil
}
// ConfirmEmail is the resolver for the confirmEmail field.
func (r *mutationResolver) ConfirmEmail(ctx context.Context, input types.ConfirmEmailInput) (*types.ConfirmEmailPayload, error) {
err := r.authSvc.ConfirmEmail(ctx, input.Token)
@@ -4153,6 +4230,31 @@ func (r *organizationResolver) Snapshots(ctx context.Context, obj *types.Organiz
return types.NewSnapshotConnection(page, r, obj.ID), nil
}
// TrustCenterFiles is the resolver for the trustCenterFiles field.
func (r *organizationResolver) TrustCenterFiles(ctx context.Context, obj *types.Organization, first *int, after *page.CursorKey, last *int, before *page.CursorKey, orderBy *types.OrderBy[coredata.TrustCenterFileOrderField]) (*types.TrustCenterFileConnection, error) {
prb := r.ProboService(ctx, obj.ID.TenantID())
pageOrderBy := page.OrderBy[coredata.TrustCenterFileOrderField]{
Field: coredata.TrustCenterFileOrderFieldCreatedAt,
Direction: page.OrderDirectionDesc,
}
if orderBy != nil {
pageOrderBy = page.OrderBy[coredata.TrustCenterFileOrderField]{
Field: orderBy.Field,
Direction: orderBy.Direction,
}
}
cursor := types.NewCursor(first, after, last, before, pageOrderBy)
pageResult, err := prb.TrustCenterFiles.ListForOrganizationID(ctx, obj.ID, cursor)
if err != nil {
panic(fmt.Errorf("cannot list organization trust center files: %w", err))
}
return types.NewTrustCenterFileConnection(pageResult, obj.ID), nil
}
// TrustCenter is the resolver for the trustCenter field.
func (r *organizationResolver) TrustCenter(ctx context.Context, obj *types.Organization) (*types.TrustCenter, error) {
prb := r.ProboService(ctx, obj.ID.TenantID())
@@ -4930,6 +5032,29 @@ func (r *trustCenterDocumentAccessResolver) Report(ctx context.Context, obj *typ
return types.NewReport(report), nil
}
// TrustCenterFile is the resolver for the trustCenterFile field.
func (r *trustCenterDocumentAccessResolver) TrustCenterFile(ctx context.Context, obj *types.TrustCenterDocumentAccess) (*types.TrustCenterFile, error) {
prb := r.ProboService(ctx, obj.ID.TenantID())
documentAccess, err := prb.TrustCenterAccesses.GetDocumentAccess(ctx, obj.ID)
if err != nil {
return nil, fmt.Errorf("cannot load trust center document access: %w", err)
}
if documentAccess.TrustCenterFileID == nil {
return nil, nil
}
trustCenterFile, err := prb.TrustCenterFiles.Get(ctx, &probo.GetTrustCenterFileRequest{
ID: *documentAccess.TrustCenterFileID,
})
if err != nil {
return nil, fmt.Errorf("cannot load trust center file: %w", err)
}
return types.NewTrustCenterFile(trustCenterFile), nil
}
// TotalCount is the resolver for the totalCount field.
func (r *trustCenterDocumentAccessConnectionResolver) TotalCount(ctx context.Context, obj *types.TrustCenterDocumentAccessConnection) (int, error) {
prb := r.ProboService(ctx, obj.ParentID.TenantID())
@@ -4942,6 +5067,48 @@ func (r *trustCenterDocumentAccessConnectionResolver) TotalCount(ctx context.Con
return count, nil
}
// FileURL is the resolver for the fileUrl field.
func (r *trustCenterFileResolver) FileURL(ctx context.Context, obj *types.TrustCenterFile) (string, error) {
prb := r.ProboService(ctx, obj.ID.TenantID())
fileURL, err := prb.TrustCenterFiles.GenerateFileURL(ctx, obj.ID, 1*time.Hour)
if err != nil {
panic(fmt.Errorf("failed to generate file URL: %w", err))
}
return fileURL, nil
}
// Organization is the resolver for the organization field.
func (r *trustCenterFileResolver) Organization(ctx context.Context, obj *types.TrustCenterFile) (*types.Organization, error) {
prb := r.ProboService(ctx, obj.ID.TenantID())
file, err := prb.TrustCenterFiles.Get(ctx, &probo.GetTrustCenterFileRequest{
ID: obj.ID,
})
if err != nil {
panic(fmt.Errorf("cannot get trust center file: %w", err))
}
organization, err := prb.Organizations.Get(ctx, file.OrganizationID)
if err != nil {
panic(fmt.Errorf("cannot get organization: %w", err))
}
return types.NewOrganization(organization), nil
}
// TotalCount is the resolver for the totalCount field.
func (r *trustCenterFileConnectionResolver) TotalCount(ctx context.Context, obj *types.TrustCenterFileConnection) (int, error) {
prb := r.ProboService(ctx, obj.ParentID.TenantID())
count, err := prb.TrustCenterFiles.CountForOrganizationID(ctx, obj.ParentID)
if err != nil {
panic(fmt.Errorf("cannot count trust center files: %w", err))
}
return count, nil
}
// LogoURL is the resolver for the logoUrl field.
func (r *trustCenterReferenceResolver) LogoURL(ctx context.Context, obj *types.TrustCenterReference) (string, error) {
prb := r.ProboService(ctx, obj.ID.TenantID())
@@ -5563,6 +5730,16 @@ func (r *Resolver) TrustCenterDocumentAccessConnection() schema.TrustCenterDocum
return &trustCenterDocumentAccessConnectionResolver{r}
}
// TrustCenterFile returns schema.TrustCenterFileResolver implementation.
func (r *Resolver) TrustCenterFile() schema.TrustCenterFileResolver {
return &trustCenterFileResolver{r}
}
// TrustCenterFileConnection returns schema.TrustCenterFileConnectionResolver implementation.
func (r *Resolver) TrustCenterFileConnection() schema.TrustCenterFileConnectionResolver {
return &trustCenterFileConnectionResolver{r}
}
// TrustCenterReference returns schema.TrustCenterReferenceResolver implementation.
func (r *Resolver) TrustCenterReference() schema.TrustCenterReferenceResolver {
return &trustCenterReferenceResolver{r}
@@ -5658,6 +5835,8 @@ type trustCenterResolver struct{ *Resolver }
type trustCenterAccessResolver struct{ *Resolver }
type trustCenterDocumentAccessResolver struct{ *Resolver }
type trustCenterDocumentAccessConnectionResolver struct{ *Resolver }
type trustCenterFileResolver struct{ *Resolver }
type trustCenterFileConnectionResolver struct{ *Resolver }
type trustCenterReferenceResolver struct{ *Resolver }
type trustCenterReferenceConnectionResolver struct{ *Resolver }
type userConnectionResolver struct{ *Resolver }

View File

@@ -476,6 +476,24 @@ type TrustCenterReferenceEdge {
node: TrustCenterReference!
}
type TrustCenterFile implements Node {
id: ID!
name: String!
category: String!
isUserAuthorized: Boolean! @goField(forceResolver: true)
hasUserRequestedAccess: Boolean! @goField(forceResolver: true)
}
type TrustCenterFileConnection {
edges: [TrustCenterFileEdge!]!
pageInfo: PageInfo!
}
type TrustCenterFileEdge {
cursor: CursorKey!
node: TrustCenterFile!
}
type TrustCenter implements Node {
id: ID!
active: Boolean!
@@ -513,6 +531,13 @@ type TrustCenter implements Node {
last: Int
before: CursorKey
): TrustCenterReferenceConnection! @goField(forceResolver: true)
trustCenterFiles(
first: Int
after: CursorKey
last: Int
before: CursorKey
): TrustCenterFileConnection! @goField(forceResolver: true)
}
type TrustCenterAccess implements Node {
@@ -559,6 +584,17 @@ input RequestReportAccessInput {
name: String
}
input RequestTrustCenterFileAccessInput {
trustCenterId: ID!
trustCenterFileId: ID!
email: String
name: String
}
input ExportTrustCenterFileInput {
trustCenterFileId: ID!
}
type ExportDocumentPDFPayload {
data: String!
}
@@ -567,6 +603,10 @@ type ExportReportPDFPayload {
data: String!
}
type ExportTrustCenterFilePayload {
data: String!
}
type AcceptNonDisclosureAgreementPayload {
success: Boolean!
}
@@ -598,4 +638,12 @@ type Mutation {
requestReportAccess(
input: RequestReportAccessInput!
): RequestAccessesPayload! @mustBeAuthenticated(role: NONE)
requestTrustCenterFileAccess(
input: RequestTrustCenterFileAccessInput!
): RequestAccessesPayload! @mustBeAuthenticated(role: NONE)
exportTrustCenterFile(
input: ExportTrustCenterFileInput!
): ExportTrustCenterFilePayload! @mustBeAuthenticated(role: NONE)
}

File diff suppressed because it is too large Load Diff

View File

@@ -148,6 +148,7 @@ func slackHandler(trustSvc *trust.Service, slackSigningSecret string, logger *lo
var documentIDs []gid.GID
var reportIDs []gid.GID
var fileIDs []gid.GID
switch action.ActionID {
case "accept_all":
@@ -157,9 +158,9 @@ func slackHandler(trustSvc *trust.Service, slackSigningSecret string, logger *lo
return
}
documentIDs, reportIDs, err = tenantSvc.SlackMessages.GetSlackMessageMetadataByID(ctx, currentMessageId)
documentIDs, reportIDs, fileIDs, err = tenantSvc.SlackMessages.GetSlackMessageDocumentIDs(ctx, currentMessageId)
if err != nil {
logger.ErrorCtx(ctx, "cannot load slack message metadata by ID", log.Error(err))
logger.ErrorCtx(ctx, "cannot load slack message document ids", log.Error(err))
httpserver.RenderJSON(w, http.StatusInternalServerError, SlackInteractiveResponse{Success: false, Message: "internal server error"})
return
}
@@ -180,6 +181,14 @@ func slackHandler(trustSvc *trust.Service, slackSigningSecret string, logger *lo
}
reportIDs = []gid.GID{repID}
case "accept_file":
fileID, err := gid.ParseGID(action.Value)
if err != nil {
httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: "invalid file ID"})
return
}
fileIDs = []gid.GID{fileID}
default:
httpserver.RenderJSON(w, http.StatusBadRequest, SlackInteractiveResponse{Success: false, Message: fmt.Sprintf("unknown action: %s", action.ActionID)})
return
@@ -191,6 +200,7 @@ func slackHandler(trustSvc *trust.Service, slackSigningSecret string, logger *lo
requesterEmail,
documentIDs,
reportIDs,
fileIDs,
); err != nil {
logger.ErrorCtx(ctx, "failed to grant access", log.Error(err))
httpserver.RenderJSON(w, http.StatusInternalServerError, SlackInteractiveResponse{Success: false, Message: "internal server error"})

View File

@@ -0,0 +1,49 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package types
import (
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/page"
)
func NewTrustCenterFileConnection(
p *page.Page[*coredata.TrustCenterFile, coredata.TrustCenterFileOrderField],
) *TrustCenterFileConnection {
edges := make([]*TrustCenterFileEdge, len(p.Data))
for i, trustCenterFile := range p.Data {
edges[i] = NewTrustCenterFileEdge(trustCenterFile, p.Cursor.OrderBy.Field)
}
return &TrustCenterFileConnection{
Edges: edges,
PageInfo: NewPageInfo(p),
}
}
func NewTrustCenterFile(f *coredata.TrustCenterFile) *TrustCenterFile {
return &TrustCenterFile{
ID: f.ID,
Name: f.Name,
Category: f.Category,
}
}
func NewTrustCenterFileEdge(f *coredata.TrustCenterFile, orderField coredata.TrustCenterFileOrderField) *TrustCenterFileEdge {
return &TrustCenterFileEdge{
Node: NewTrustCenterFile(f),
Cursor: f.CursorKey(orderField),
}
}

View File

@@ -83,6 +83,14 @@ type ExportReportPDFPayload struct {
Data string `json:"data"`
}
type ExportTrustCenterFileInput struct {
TrustCenterFileID gid.GID `json:"trustCenterFileId"`
}
type ExportTrustCenterFilePayload struct {
Data string `json:"data"`
}
type Framework struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
@@ -151,6 +159,13 @@ type RequestReportAccessInput struct {
Name *string `json:"name,omitempty"`
}
type RequestTrustCenterFileAccessInput struct {
TrustCenterID gid.GID `json:"trustCenterId"`
TrustCenterFileID gid.GID `json:"trustCenterFileId"`
Email *string `json:"email,omitempty"`
Name *string `json:"name,omitempty"`
}
type TrustCenter struct {
ID gid.GID `json:"id"`
Active bool `json:"active"`
@@ -164,6 +179,7 @@ type TrustCenter struct {
Audits *AuditConnection `json:"audits"`
Vendors *VendorConnection `json:"vendors"`
References *TrustCenterReferenceConnection `json:"references"`
TrustCenterFiles *TrustCenterFileConnection `json:"trustCenterFiles"`
}
func (TrustCenter) IsNode() {}
@@ -180,6 +196,27 @@ type TrustCenterAccess struct {
func (TrustCenterAccess) IsNode() {}
func (this TrustCenterAccess) GetID() gid.GID { return this.ID }
type TrustCenterFile struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
Category string `json:"category"`
IsUserAuthorized bool `json:"isUserAuthorized"`
HasUserRequestedAccess bool `json:"hasUserRequestedAccess"`
}
func (TrustCenterFile) IsNode() {}
func (this TrustCenterFile) GetID() gid.GID { return this.ID }
type TrustCenterFileConnection struct {
Edges []*TrustCenterFileEdge `json:"edges"`
PageInfo *PageInfo `json:"pageInfo"`
}
type TrustCenterFileEdge struct {
Cursor page.CursorKey `json:"cursor"`
Node *TrustCenterFile `json:"node"`
}
type TrustCenterReference struct {
ID gid.GID `json:"id"`
Name string `json:"name"`

View File

@@ -445,6 +445,138 @@ func (r *mutationResolver) RequestReportAccess(ctx context.Context, input types.
}, nil
}
// RequestTrustCenterFileAccess is the resolver for the requestTrustCenterFileAccess field.
func (r *mutationResolver) RequestTrustCenterFileAccess(ctx context.Context, input types.RequestTrustCenterFileAccessInput) (*types.RequestAccessesPayload, error) {
publicTrustService := r.PublicTrustService(ctx, input.TrustCenterID.TenantID())
trustCenterFile, err := publicTrustService.TrustCenterFiles.Get(ctx, input.TrustCenterFileID)
if err != nil {
panic(fmt.Errorf("cannot load trust center file: %w", err))
}
if trustCenterFile.TrustCenterVisibility == coredata.TrustCenterVisibilityPublic {
return nil, fmt.Errorf("trust center file is publicly available and does not require access request")
}
userData := r.UserFromContext(ctx)
if userData != nil {
return nil, fmt.Errorf("session users cannot request trust center access")
}
email := input.Email
tokenData := TokenAccessFromContext(ctx)
if tokenData != nil {
if email != nil || input.Name != nil {
return nil, fmt.Errorf("email and name are not allowed for authenticated users")
}
emailValue := tokenData.GetEmail()
email = &emailValue
}
if email == nil {
return nil, fmt.Errorf("email is required for unauthenticated users")
}
access, err := publicTrustService.TrustCenterAccesses.Request(ctx, &trust.TrustCenterAccessRequest{
TrustCenterID: input.TrustCenterID,
Email: *email,
Name: input.Name,
DocumentIDs: []gid.GID{},
ReportIDs: []gid.GID{},
TrustCenterFileIDs: []gid.GID{input.TrustCenterFileID},
})
if err != nil {
panic(fmt.Errorf("cannot request trust center file access: %w", err))
}
return &types.RequestAccessesPayload{
TrustCenterAccess: &types.TrustCenterAccess{
ID: access.ID,
Email: access.Email,
Name: access.Name,
CreatedAt: access.CreatedAt,
UpdatedAt: access.UpdatedAt,
},
}, nil
}
// ExportTrustCenterFile is the resolver for the exportTrustCenterFile field.
func (r *mutationResolver) ExportTrustCenterFile(ctx context.Context, input types.ExportTrustCenterFileInput) (*types.ExportTrustCenterFilePayload, error) {
publicTrustService := r.PublicTrustService(ctx, input.TrustCenterFileID.TenantID())
trustCenterFile, err := publicTrustService.TrustCenterFiles.Get(ctx, input.TrustCenterFileID)
if err != nil {
panic(fmt.Errorf("cannot load trust center file: %w", err))
}
if trustCenterFile.TrustCenterVisibility == coredata.TrustCenterVisibilityPublic {
fileData, err := publicTrustService.TrustCenterFiles.ExportFileWithoutWatermark(ctx, input.TrustCenterFileID)
if err != nil {
panic(fmt.Errorf("cannot export trust center file: %w", err))
}
return &types.ExportTrustCenterFilePayload{
Data: fmt.Sprintf("data:application/pdf;base64,%s", base64.StdEncoding.EncodeToString(fileData)),
}, nil
}
privateTrustService, err := r.PrivateTrustService(ctx, input.TrustCenterFileID.TenantID())
if err != nil {
return nil, fmt.Errorf("cannot export trust center file: %w", err)
}
tokenData := TokenAccessFromContext(ctx)
if tokenData != nil {
ndaExists := true
hasAcceptedNDA := false
trustCenter, _, err := privateTrustService.TrustCenters.Get(ctx, tokenData.TrustCenterID)
if err != nil {
panic(fmt.Errorf("cannot get trust center: %w", err))
}
if trustCenter.NonDisclosureAgreementFileID == nil {
ndaExists = false
}
if ndaExists {
hasAcceptedNDA, err = privateTrustService.TrustCenterAccesses.HasAcceptedNonDisclosureAgreement(ctx, tokenData.TrustCenterID, tokenData.GetEmail())
if err != nil {
panic(fmt.Errorf("cannot check if user has accepted NDA: %w", err))
}
}
fileAccess, err := privateTrustService.TrustCenterAccesses.LoadTrustCenterFileAccess(ctx, tokenData.TrustCenterID, tokenData.GetEmail(), input.TrustCenterFileID)
if err != nil {
panic(fmt.Errorf("cannot check trust center file access: %w", err))
}
if !fileAccess.Active {
return nil, fmt.Errorf("access denied: no permission to access this file")
}
if ndaExists && !hasAcceptedNDA {
return nil, fmt.Errorf("user has not accepted NDA")
}
}
userData := UserFromContext(ctx)
userEmail := ""
if userData != nil {
userEmail = userData.EmailAddress
}
if tokenData != nil {
userEmail = tokenData.GetEmail()
}
fileData, err := privateTrustService.TrustCenterFiles.ExportFile(ctx, input.TrustCenterFileID, userEmail)
if err != nil {
panic(fmt.Errorf("cannot export trust center file: %w", err))
}
return &types.ExportTrustCenterFilePayload{
Data: fmt.Sprintf("data:application/pdf;base64,%s", base64.StdEncoding.EncodeToString(fileData)),
}, nil
}
// LogoURL is the resolver for the logoUrl field.
func (r *organizationResolver) LogoURL(ctx context.Context, obj *types.Organization) (*string, error) {
publicTrustService := r.PublicTrustService(ctx, obj.ID.TenantID())
@@ -772,6 +904,84 @@ func (r *trustCenterResolver) References(ctx context.Context, obj *types.TrustCe
return types.NewTrustCenterReferenceConnection(referencePage), nil
}
// TrustCenterFiles is the resolver for the trustCenterFiles field.
func (r *trustCenterResolver) TrustCenterFiles(ctx context.Context, obj *types.TrustCenter, first *int, after *page.CursorKey, last *int, before *page.CursorKey) (*types.TrustCenterFileConnection, error) {
publicTrustService := r.PublicTrustService(ctx, obj.ID.TenantID())
pageOrderBy := page.OrderBy[coredata.TrustCenterFileOrderField]{
Field: coredata.TrustCenterFileOrderFieldName,
Direction: page.OrderDirectionAsc,
}
cursor := types.NewCursor(first, after, last, before, pageOrderBy)
trustCenterFilePage, err := publicTrustService.TrustCenterFiles.ListForOrganizationId(ctx, obj.Organization.ID, cursor)
if err != nil {
panic(fmt.Errorf("cannot list public trust center files: %w", err))
}
return types.NewTrustCenterFileConnection(trustCenterFilePage), nil
}
// IsUserAuthorized is the resolver for the isUserAuthorized field.
func (r *trustCenterFileResolver) IsUserAuthorized(ctx context.Context, obj *types.TrustCenterFile) (bool, error) {
publicTrustService := r.PublicTrustService(ctx, obj.ID.TenantID())
trustCenterFile, err := publicTrustService.TrustCenterFiles.Get(ctx, obj.ID)
if err != nil {
panic(fmt.Errorf("cannot load trust center file: %w", err))
}
if trustCenterFile.TrustCenterVisibility == coredata.TrustCenterVisibilityPublic {
return true, nil
}
privateTrustService, err := r.PrivateTrustService(ctx, obj.ID.TenantID())
if err != nil {
return false, nil
}
userData := r.UserFromContext(ctx)
if userData != nil {
return true, nil
}
tokenData := TokenAccessFromContext(ctx)
if tokenData != nil {
fileAccess, err := privateTrustService.TrustCenterAccesses.LoadTrustCenterFileAccess(ctx, tokenData.TrustCenterID, tokenData.GetEmail(), obj.ID)
if err != nil {
return false, nil
}
return fileAccess.Active, nil
}
panic(fmt.Errorf("no user or token data found"))
}
// HasUserRequestedAccess is the resolver for the hasUserRequestedAccess field.
func (r *trustCenterFileResolver) HasUserRequestedAccess(ctx context.Context, obj *types.TrustCenterFile) (bool, error) {
privateTrustService, err := r.PrivateTrustService(ctx, obj.ID.TenantID())
if err != nil {
return false, nil
}
userData := r.UserFromContext(ctx)
if userData != nil {
return false, nil
}
tokenData := TokenAccessFromContext(ctx)
if tokenData != nil {
_, err := privateTrustService.TrustCenterAccesses.LoadTrustCenterFileAccess(ctx, tokenData.TrustCenterID, tokenData.GetEmail(), obj.ID)
if err != nil {
return false, nil
}
return true, nil
}
return false, nil
}
// LogoURL is the resolver for the logoUrl field.
func (r *trustCenterReferenceResolver) LogoURL(ctx context.Context, obj *types.TrustCenterReference) (string, error) {
publicTrustService := r.PublicTrustService(ctx, obj.ID.TenantID())
@@ -805,6 +1015,11 @@ func (r *Resolver) Report() schema.ReportResolver { return &reportResolver{r} }
// TrustCenter returns schema.TrustCenterResolver implementation.
func (r *Resolver) TrustCenter() schema.TrustCenterResolver { return &trustCenterResolver{r} }
// TrustCenterFile returns schema.TrustCenterFileResolver implementation.
func (r *Resolver) TrustCenterFile() schema.TrustCenterFileResolver {
return &trustCenterFileResolver{r}
}
// TrustCenterReference returns schema.TrustCenterReferenceResolver implementation.
func (r *Resolver) TrustCenterReference() schema.TrustCenterReferenceResolver {
return &trustCenterReferenceResolver{r}
@@ -817,4 +1032,5 @@ type organizationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }
type reportResolver struct{ *Resolver }
type trustCenterResolver struct{ *Resolver }
type trustCenterFileResolver struct{ *Resolver }
type trustCenterReferenceResolver struct{ *Resolver }

View File

@@ -74,6 +74,7 @@ type (
Frameworks *FrameworkService
TrustCenterAccesses *TrustCenterAccessService
TrustCenterReferences *TrustCenterReferenceService
TrustCenterFiles *TrustCenterFileService
Reports *ReportService
Organizations *OrganizationService
SlackMessages *SlackMessageService
@@ -136,6 +137,7 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
tenantService.Frameworks = &FrameworkService{svc: tenantService}
tenantService.TrustCenterAccesses = &TrustCenterAccessService{svc: tenantService, auth: s.auth, logger: s.logger}
tenantService.TrustCenterReferences = &TrustCenterReferenceService{svc: tenantService}
tenantService.TrustCenterFiles = &TrustCenterFileService{svc: tenantService}
tenantService.Reports = &ReportService{svc: tenantService}
tenantService.Organizations = &OrganizationService{svc: tenantService}
tenantService.SlackMessages = &SlackMessageService{svc: tenantService, slackClient: slackClient}

View File

@@ -51,9 +51,17 @@ type (
Granted bool
}
SlackMessageFile struct {
ID string
Name string
Category string
Granted bool
}
SlackMessageMetadata struct {
Documents []SlackMessageDocument
Reports []SlackMessageReport
Files []SlackMessageFile
}
)
@@ -61,6 +69,7 @@ func (m SlackMessageMetadata) toMap() map[string]any {
return map[string]any{
"documents": m.Documents,
"reports": m.Reports,
"files": m.Files,
}
}
@@ -86,10 +95,10 @@ func (s *Service) GetInitialSlackMessageByChannelAndTS(
return &slackMessage, nil
}
func (s *SlackMessageService) GetSlackMessageMetadataByID(
func (s *SlackMessageService) GetSlackMessageDocumentIDs(
ctx context.Context,
slackMessageID gid.GID,
) (documentIDs []gid.GID, reportIDs []gid.GID, err error) {
) (documentIDs []gid.GID, reportIDs []gid.GID, fileIDs []gid.GID, err error) {
var slackMessage coredata.SlackMessage
err = s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
@@ -101,52 +110,14 @@ func (s *SlackMessageService) GetSlackMessageMetadataByID(
})
if err != nil {
return nil, nil, err
return nil, nil, nil, err
}
documents, ok := slackMessage.Metadata["documents"].([]any)
if !ok {
return nil, nil, fmt.Errorf("invalid documents metadata")
}
documentIDs = extractIDsFromMetadata(slackMessage.Metadata, "documents")
reportIDs = extractIDsFromMetadata(slackMessage.Metadata, "reports")
fileIDs = extractIDsFromMetadata(slackMessage.Metadata, "files")
for _, docAny := range documents {
doc, ok := docAny.(map[string]any)
if !ok {
continue
}
idStr, ok := doc["ID"].(string)
if !ok {
continue
}
docID, err := gid.ParseGID(idStr)
if err != nil {
continue
}
documentIDs = append(documentIDs, docID)
}
reports, ok := slackMessage.Metadata["reports"].([]any)
if !ok {
return nil, nil, fmt.Errorf("invalid reports metadata")
}
for _, repAny := range reports {
rep, ok := repAny.(map[string]any)
if !ok {
continue
}
idStr, ok := rep["ID"].(string)
if !ok {
continue
}
repID, err := gid.ParseGID(idStr)
if err != nil {
continue
}
reportIDs = append(reportIDs, repID)
}
return documentIDs, reportIDs, nil
return documentIDs, reportIDs, fileIDs, nil
}
func (s *SlackMessageService) UpdateSlackAccessMessage(
@@ -171,7 +142,7 @@ func (s *SlackMessageService) UpdateSlackAccessMessage(
return fmt.Errorf("cannot load trust center access: %w", err)
}
documents, reports, err := s.loadDocumentsAndReportsFromAccesses(ctx, tx, trustCenterAccess.ID)
documents, reports, files, err := s.loadDocumentsReportsAndFilesFromAccesses(ctx, tx, trustCenterAccess.ID)
if err != nil {
return err
}
@@ -185,6 +156,7 @@ func (s *SlackMessageService) UpdateSlackAccessMessage(
trustCenter.OrganizationID,
documents,
reports,
files,
)
if err != nil {
return err
@@ -193,6 +165,7 @@ func (s *SlackMessageService) UpdateSlackAccessMessage(
metadata := SlackMessageMetadata{
Documents: documents,
Reports: reports,
Files: files,
}
now := time.Now()
@@ -261,9 +234,9 @@ func (s *SlackMessageService) QueueSlackNotification(
return fmt.Errorf("no slack connector found for organization")
}
documents, reports, err := s.loadDocumentsAndReportsFromAccesses(ctx, tx, trustCenterAccess.ID)
documents, reports, files, err := s.loadDocumentsReportsAndFilesFromAccesses(ctx, tx, trustCenterAccess.ID)
if err != nil {
return fmt.Errorf("cannot load documents and reports: %w", err)
return fmt.Errorf("cannot load documents, reports and files: %w", err)
}
slackMessageID := gid.New(s.svc.scope.GetTenantID(), coredata.SlackMessageEntityType)
@@ -275,6 +248,7 @@ func (s *SlackMessageService) QueueSlackNotification(
trustCenter.OrganizationID,
documents,
reports,
files,
)
if err != nil {
return fmt.Errorf("cannot build access request message: %w", err)
@@ -283,6 +257,7 @@ func (s *SlackMessageService) QueueSlackNotification(
metadata := SlackMessageMetadata{
Documents: documents,
Reports: reports,
Files: files,
}
now := time.Now()
@@ -334,28 +309,30 @@ func (s *SlackMessageService) QueueSlackNotification(
})
}
func (s *SlackMessageService) loadDocumentsAndReportsFromAccesses(
func (s *SlackMessageService) loadDocumentsReportsAndFilesFromAccesses(
ctx context.Context,
conn pg.Conn,
trustCenterAccessID gid.GID,
) (
documents []SlackMessageDocument,
reports []SlackMessageReport,
files []SlackMessageFile,
err error,
) {
documents = []SlackMessageDocument{}
reports = []SlackMessageReport{}
files = []SlackMessageFile{}
var accesses coredata.TrustCenterDocumentAccesses
if err := accesses.LoadAllByTrustCenterAccessID(ctx, conn, s.svc.scope, trustCenterAccessID); err != nil {
return nil, nil, fmt.Errorf("cannot load trust center document accesses: %w", err)
return nil, nil, nil, fmt.Errorf("cannot load trust center document accesses: %w", err)
}
for _, access := range accesses {
if access.DocumentID != nil {
doc := &coredata.Document{}
if err := doc.LoadByID(ctx, conn, s.svc.scope, *access.DocumentID); err != nil {
return nil, nil, fmt.Errorf("cannot load document: %w", err)
return nil, nil, nil, fmt.Errorf("cannot load document: %w", err)
}
documents = append(documents, SlackMessageDocument{
ID: access.DocumentID.String(),
@@ -367,17 +344,17 @@ func (s *SlackMessageService) loadDocumentsAndReportsFromAccesses(
if access.ReportID != nil {
rep := &coredata.Report{}
if err := rep.LoadByID(ctx, conn, s.svc.scope, *access.ReportID); err != nil {
return nil, nil, fmt.Errorf("cannot load report: %w", err)
return nil, nil, nil, fmt.Errorf("cannot load report: %w", err)
}
audit := &coredata.Audit{}
if err := audit.LoadByReportID(ctx, conn, s.svc.scope, *access.ReportID); err != nil {
return nil, nil, fmt.Errorf("cannot load audit: %w", err)
return nil, nil, nil, fmt.Errorf("cannot load audit: %w", err)
}
framework := &coredata.Framework{}
if err := framework.LoadByID(ctx, conn, s.svc.scope, audit.FrameworkID); err != nil {
return nil, nil, fmt.Errorf("cannot load framework: %w", err)
return nil, nil, nil, fmt.Errorf("cannot load framework: %w", err)
}
label := framework.Name
@@ -391,9 +368,22 @@ func (s *SlackMessageService) loadDocumentsAndReportsFromAccesses(
Granted: access.Active,
})
}
if access.TrustCenterFileID != nil {
file := &coredata.TrustCenterFile{}
if err := file.LoadByID(ctx, conn, s.svc.scope, *access.TrustCenterFileID); err != nil {
return nil, nil, nil, fmt.Errorf("cannot load trust center file: %w", err)
}
files = append(files, SlackMessageFile{
ID: access.TrustCenterFileID.String(),
Name: file.Name,
Category: file.Category,
Granted: access.Active,
})
}
}
return documents, reports, nil
return documents, reports, files, nil
}
func (s *SlackMessageService) buildAccessRequestMessage(
@@ -403,9 +393,11 @@ func (s *SlackMessageService) buildAccessRequestMessage(
organizationID gid.GID,
documents []SlackMessageDocument,
reports []SlackMessageReport,
files []SlackMessageFile,
) (map[string]any, error) {
var documentIDs []string
var reportIDs []string
var fileIDs []string
for _, doc := range documents {
documentIDs = append(documentIDs, doc.ID)
@@ -413,6 +405,9 @@ func (s *SlackMessageService) buildAccessRequestMessage(
for _, rep := range reports {
reportIDs = append(reportIDs, rep.ID)
}
for _, file := range files {
fileIDs = append(fileIDs, file.ID)
}
templateData := struct {
RequesterName string
@@ -422,8 +417,10 @@ func (s *SlackMessageService) buildAccessRequestMessage(
SlackMessageID string
DocumentIDs []string
ReportIDs []string
FileIDs []string
Documents []SlackMessageDocument
Reports []SlackMessageReport
Files []SlackMessageFile
}{
RequesterName: requesterName,
RequesterEmail: requesterEmail,
@@ -432,8 +429,10 @@ func (s *SlackMessageService) buildAccessRequestMessage(
SlackMessageID: slackMessageID.String(),
DocumentIDs: documentIDs,
ReportIDs: reportIDs,
FileIDs: fileIDs,
Documents: documents,
Reports: reports,
Files: files,
}
var buf bytes.Buffer
@@ -448,3 +447,30 @@ func (s *SlackMessageService) buildAccessRequestMessage(
return body, nil
}
func extractIDsFromMetadata(metadata map[string]any, fieldName string) []gid.GID {
ids := []gid.GID{}
items, ok := metadata[fieldName].([]any)
if !ok || items == nil {
return ids
}
for _, itemAny := range items {
item, ok := itemAny.(map[string]any)
if !ok {
continue
}
idStr, ok := item["ID"].(string)
if !ok {
continue
}
id, err := gid.ParseGID(idStr)
if err != nil {
continue
}
ids = append(ids, id)
}
return ids
}

View File

@@ -107,6 +107,40 @@
"value": "{{.ID}}",
"style": "primary"
}{{end}}
}{{end}}{{end}}{{if .Files}},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*📎 Requested Files*"
}
}{{range .Files}},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "<https://{{$.Domain}}/organizations/{{$.OrganizationID}}/trust-center/files|{{jsonEscape .Name}}>{{if .Category}} ({{jsonEscape .Category}}){{end}}"
},
"accessory": {{if .Granted}}{
"type": "button",
"text": {
"type": "plain_text",
"text": "✓ Granted"
},
"url": "https://{{$.Domain}}/organizations/{{$.OrganizationID}}/trust-center/access"
}{{else}}{
"type": "button",
"text": {
"type": "plain_text",
"text": "Accept"
},
"action_id": "accept_file",
"value": "{{.ID}}",
"style": "primary"
}{{end}}
}{{end}}{{end}},
{
"type": "context",

View File

@@ -67,11 +67,12 @@ type (
}
TrustCenterAccessRequest struct {
TrustCenterID gid.GID
Email string
Name *string
DocumentIDs []gid.GID
ReportIDs []gid.GID
TrustCenterID gid.GID
Email string
Name *string
DocumentIDs []gid.GID
ReportIDs []gid.GID
TrustCenterFileIDs []gid.GID
}
)
@@ -145,6 +146,20 @@ func (s TrustCenterAccessService) Request(
}
}
}
trustCenterFileIDs := req.TrustCenterFileIDs
if req.TrustCenterFileIDs == nil {
var allTrustCenterFiles coredata.TrustCenterFiles
if err := allTrustCenterFiles.LoadAllByOrganizationID(ctx, tx, s.svc.scope, organizationID); err != nil {
return fmt.Errorf("cannot list trust center files: %w", err)
}
for _, file := range allTrustCenterFiles {
trustCenterFileIDs = append(trustCenterFileIDs, file.ID)
}
}
existingAccess := &coredata.TrustCenterAccess{}
err := existingAccess.LoadByTrustCenterIDAndEmail(ctx, tx, s.svc.scope, req.TrustCenterID, req.Email)
@@ -186,9 +201,10 @@ func (s TrustCenterAccessService) Request(
return fmt.Errorf("cannot load existing access records: %w", err)
}
existingDocumentIDs, existingReportIDs := extractExistingIDs(existingAccesses)
existingDocumentIDs, existingReportIDs, existingTrustCenterFileIDs := extractExistingIDs(existingAccesses)
newDocumentIDs := filterExistingIDs(documentIDs, existingDocumentIDs)
newReportIDs := filterExistingIDs(reportIDs, existingReportIDs)
newTrustCenterFileIDs := filterExistingIDs(trustCenterFileIDs, existingTrustCenterFileIDs)
var accesses coredata.TrustCenterDocumentAccesses
@@ -200,6 +216,10 @@ func (s TrustCenterAccessService) Request(
return fmt.Errorf("cannot bulk insert trust center report accesses: %w", err)
}
if err := accesses.BulkInsertTrustCenterFileAccesses(ctx, tx, s.svc.scope, access.ID, newTrustCenterFileIDs, now); err != nil {
return fmt.Errorf("cannot bulk insert trust center file accesses: %w", err)
}
return nil
})
@@ -335,12 +355,48 @@ func (s TrustCenterAccessService) LoadReportAccess(
return reportAccess, nil
}
func (s TrustCenterAccessService) LoadTrustCenterFileAccess(
ctx context.Context,
trustCenterID gid.GID,
email string,
trustCenterFileID gid.GID,
) (*coredata.TrustCenterDocumentAccess, error) {
var fileAccess *coredata.TrustCenterDocumentAccess
err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
access := &coredata.TrustCenterAccess{}
err := access.LoadByTrustCenterIDAndEmail(ctx, conn, s.svc.scope, trustCenterID, email)
if err != nil {
return fmt.Errorf("cannot load trust center access: %w", err)
}
if !access.Active {
return fmt.Errorf("trust center access is not active")
}
fileAccess = &coredata.TrustCenterDocumentAccess{}
err = fileAccess.LoadByTrustCenterAccessIDAndTrustCenterFileID(ctx, conn, s.svc.scope, access.ID, trustCenterFileID)
if err != nil {
return fmt.Errorf("cannot load trust center file access: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
return fileAccess, nil
}
func (s *TrustCenterAccessService) AcceptByIDs(
ctx context.Context,
organizationID gid.GID,
email string,
documentIDs []gid.GID,
reportIDs []gid.GID,
fileIDs []gid.GID,
) error {
return s.svc.pg.WithTx(ctx, func(tx pg.Conn) error {
trustCenter := &coredata.TrustCenter{}
@@ -366,6 +422,11 @@ func (s *TrustCenterAccessService) AcceptByIDs(
return fmt.Errorf("cannot activate report accesses: %w", err)
}
}
if len(fileIDs) > 0 {
if err := coredata.ActivateByTrustCenterFileIDs(ctx, tx, s.svc.scope, access.ID, fileIDs, now); err != nil {
return fmt.Errorf("cannot activate trust center file accesses: %w", err)
}
}
if wasInactive {
access.Active = true
@@ -470,9 +531,10 @@ func (s *TrustCenterAccessService) sendTrustCenterAccessEmail(
return nil
}
func extractExistingIDs(accesses coredata.TrustCenterDocumentAccesses) ([]gid.GID, []gid.GID) {
func extractExistingIDs(accesses coredata.TrustCenterDocumentAccesses) ([]gid.GID, []gid.GID, []gid.GID) {
var documentIDs []gid.GID
var reportIDs []gid.GID
var trustCenterFileIDs []gid.GID
for _, access := range accesses {
if access.DocumentID != nil {
@@ -481,9 +543,12 @@ func extractExistingIDs(accesses coredata.TrustCenterDocumentAccesses) ([]gid.GI
if access.ReportID != nil {
reportIDs = append(reportIDs, *access.ReportID)
}
if access.TrustCenterFileID != nil {
trustCenterFileIDs = append(trustCenterFileIDs, *access.TrustCenterFileID)
}
}
return documentIDs, reportIDs
return documentIDs, reportIDs, trustCenterFileIDs
}
func filterExistingIDs(allIDs []gid.GID, existingIDs []gid.GID) []gid.GID {

View File

@@ -0,0 +1,150 @@
// Copyright (c) 2025 Probo Inc <hello@getprobo.com>.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
package trust
import (
"context"
"fmt"
"io"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"github.com/getprobo/probo/pkg/watermarkpdf"
"go.gearno.de/kit/pg"
)
type TrustCenterFileService struct {
svc *TenantService
}
func (s *TrustCenterFileService) Get(
ctx context.Context,
trustCenterFileID gid.GID,
) (*coredata.TrustCenterFile, error) {
trustCenterFile := &coredata.TrustCenterFile{}
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
err := trustCenterFile.LoadByID(ctx, conn, s.svc.scope, trustCenterFileID)
if err != nil {
return fmt.Errorf("cannot load trust center file: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return trustCenterFile, nil
}
func (s *TrustCenterFileService) ListForOrganizationId(
ctx context.Context,
organizationID gid.GID,
cursor *page.Cursor[coredata.TrustCenterFileOrderField],
) (*page.Page[*coredata.TrustCenterFile, coredata.TrustCenterFileOrderField], error) {
var trustCenterFiles coredata.TrustCenterFiles
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
err := trustCenterFiles.LoadByOrganizationID(ctx, conn, s.svc.scope, organizationID, cursor)
if err != nil {
return fmt.Errorf("cannot load trust center files: %w", err)
}
return nil
},
)
if err != nil {
return nil, err
}
return page.NewPage(trustCenterFiles, cursor), nil
}
func (s *TrustCenterFileService) ExportFile(
ctx context.Context,
trustCenterFileID gid.GID,
email string,
) ([]byte, error) {
pdfData, err := s.exportFileData(ctx, trustCenterFileID)
if err != nil {
return nil, fmt.Errorf("cannot export trust center file: %w", err)
}
watermarkedPDF, err := watermarkpdf.AddConfidentialWithTimestamp(pdfData, email)
if err != nil {
return nil, fmt.Errorf("cannot add watermark to PDF: %w", err)
}
return watermarkedPDF, nil
}
func (s *TrustCenterFileService) ExportFileWithoutWatermark(
ctx context.Context,
trustCenterFileID gid.GID,
) ([]byte, error) {
return s.exportFileData(ctx, trustCenterFileID)
}
func (s *TrustCenterFileService) exportFileData(
ctx context.Context,
trustCenterFileID gid.GID,
) ([]byte, error) {
var trustCenterFile *coredata.TrustCenterFile
var file *coredata.File
err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
trustCenterFile = &coredata.TrustCenterFile{}
if err := trustCenterFile.LoadByID(ctx, conn, s.svc.scope, trustCenterFileID); err != nil {
return fmt.Errorf("cannot load trust center file: %w", err)
}
file = &coredata.File{}
if err := file.LoadByID(ctx, conn, s.svc.scope, trustCenterFile.FileID); err != nil {
return fmt.Errorf("cannot load file: %w", err)
}
return nil
})
if err != nil {
return nil, err
}
result, err := s.svc.s3.GetObject(ctx, &s3.GetObjectInput{
Bucket: aws.String(s.svc.bucket),
Key: aws.String(file.FileKey),
})
if err != nil {
return nil, fmt.Errorf("cannot download file from S3: %w", err)
}
defer result.Body.Close()
fileData, err := io.ReadAll(result.Body)
if err != nil {
return nil, fmt.Errorf("cannot read file data: %w", err)
}
return fileData, nil
}