Add assets

Signed-off-by: Sacha Al Himdani <sacha@getprobo.com>
This commit is contained in:
Sacha Al Himdani
2025-05-30 15:07:57 -07:00
parent b315be96bc
commit fa1cd6fb51
38 changed files with 9121 additions and 7 deletions

427
pkg/coredata/asset.go Normal file
View File

@@ -0,0 +1,427 @@
// 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 Asset struct {
ID gid.GID `db:"id"`
Name string `db:"name"`
Amount int `db:"amount"`
OwnerID gid.GID `db:"owner_id"`
OrganizationID gid.GID `db:"organization_id"`
Criticity CriticityLevel `db:"criticity"`
AssetType AssetType `db:"asset_type"`
DataTypesStored string `db:"data_types_stored"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
func (a *Asset) CursorKey(field AssetOrderField) page.CursorKey {
switch field {
case AssetOrderFieldCreatedAt:
return page.NewCursorKey(a.ID, a.CreatedAt)
case AssetOrderFieldAmount:
return page.NewCursorKey(a.ID, a.Amount)
case AssetOrderFieldCriticity:
return page.NewCursorKey(a.ID, a.Criticity)
}
panic(fmt.Sprintf("unsupported order by: %s", field))
}
type Assets []*Asset
func (a *Asset) LoadByID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
assetID gid.GID,
) error {
q := `
SELECT
id,
name,
organization_id,
owner_id,
amount,
criticity,
asset_type,
data_types_stored,
created_at,
updated_at
FROM
assets
WHERE
%s
AND id = @asset_id
LIMIT 1;
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"asset_id": assetID}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query assets: %w", err)
}
asset, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Asset])
if err != nil {
return fmt.Errorf("cannot collect asset: %w", err)
}
*a = asset
return nil
}
func (a *Asset) LoadByOwnerID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
SELECT
id,
name,
organization_id,
owner_id,
amount,
criticity,
asset_type,
data_types_stored,
created_at,
updated_at
FROM
assets
WHERE
%s
AND owner_id = @owner_id
LIMIT 1;
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"owner_id": a.OwnerID}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot query assets: %w", err)
}
asset, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Asset])
if err != nil {
return fmt.Errorf("cannot collect asset: %w", err)
}
*a = asset
return nil
}
func (a *Assets) LoadByOrganizationID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organizationID gid.GID,
cursor *page.Cursor[AssetOrderField],
) error {
q := `
SELECT
id,
name,
organization_id,
owner_id,
amount,
criticity,
asset_type,
data_types_stored,
created_at,
updated_at
FROM
assets
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 assets: %w", err)
}
assets, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Asset])
if err != nil {
return fmt.Errorf("cannot collect assets: %w", err)
}
*a = assets
return nil
}
func (a *Asset) Insert(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
INSERT INTO assets (
id,
tenant_id,
name,
organization_id,
owner_id,
amount,
criticity,
asset_type,
data_types_stored,
created_at,
updated_at
) VALUES (
@id,
@tenant_id,
@name,
@organization_id,
@owner_id,
@amount,
@criticity,
@asset_type,
@data_types_stored,
@created_at,
@updated_at
)
`
args := pgx.StrictNamedArgs{
"id": a.ID,
"tenant_id": scope.GetTenantID(),
"organization_id": a.OrganizationID,
"name": a.Name,
"owner_id": a.OwnerID,
"amount": a.Amount,
"criticity": a.Criticity,
"asset_type": a.AssetType,
"data_types_stored": a.DataTypesStored,
"created_at": a.CreatedAt,
"updated_at": a.UpdatedAt,
}
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot insert asset: %w", err)
}
return nil
}
func (a *Asset) Update(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
UPDATE assets
SET
name = @name,
owner_id = @owner_id,
amount = @amount,
criticity = @criticity,
asset_type = @asset_type,
data_types_stored = @data_types_stored,
updated_at = @updated_at
WHERE
%s
AND id = @id
RETURNING
id,
name,
organization_id,
owner_id,
amount,
criticity,
asset_type,
data_types_stored,
created_at,
updated_at
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{
"id": a.ID,
"name": a.Name,
"owner_id": a.OwnerID,
"amount": a.Amount,
"criticity": a.Criticity,
"asset_type": a.AssetType,
"data_types_stored": a.DataTypesStored,
"updated_at": time.Now(),
}
maps.Copy(args, scope.SQLArguments())
rows, err := conn.Query(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot update asset: %w", err)
}
asset, err := pgx.CollectExactlyOneRow(rows, pgx.RowToStructByName[Asset])
if err != nil {
return fmt.Errorf("cannot collect updated asset: %w", err)
}
*a = asset
return nil
}
func (a *Asset) Delete(
ctx context.Context,
conn pg.Conn,
scope Scoper,
) error {
q := `
DELETE FROM assets
WHERE
%s
AND id = @id
`
q = fmt.Sprintf(q, scope.SQLFragment())
args := pgx.StrictNamedArgs{"id": a.ID}
maps.Copy(args, scope.SQLArguments())
_, err := conn.Exec(ctx, q, args)
if err != nil {
return fmt.Errorf("cannot delete asset: %w", err)
}
return nil
}
type AssetVendor struct {
AssetID int64 `db:"asset_id"`
VendorID int64 `db:"vendor_id"`
CreatedAt time.Time `db:"created_at"`
}
func (a *Asset) CreateWithVendors(
ctx context.Context,
conn pg.Conn,
scope Scoper,
organization *Organization,
vendorIDs []gid.GID,
now time.Time,
) error {
if err := organization.LoadByID(ctx, conn, scope, a.OrganizationID); err != nil {
return fmt.Errorf("cannot load organization %q: %w", a.OrganizationID, err)
}
if err := a.Insert(ctx, conn, scope); err != nil {
return fmt.Errorf("cannot insert asset: %w", err)
}
if len(vendorIDs) > 0 {
for _, vendorID := range vendorIDs {
_, err := conn.Exec(ctx, `
INSERT INTO asset_vendors (tenant_id, asset_id, vendor_id, created_at)
VALUES ($1, $2, $3, $4)
`, scope.GetTenantID(), a.ID, vendorID, now)
if err != nil {
return fmt.Errorf("cannot insert asset vendor: %w", err)
}
}
}
return nil
}
func (a *Asset) UpdateWithVendors(
ctx context.Context,
conn pg.Conn,
scope Scoper,
vendorIDs []gid.GID,
now time.Time,
) error {
existing := &Asset{}
if err := existing.LoadByID(ctx, conn, scope, a.ID); err != nil {
return fmt.Errorf("cannot load asset: %w", err)
}
a.OrganizationID = existing.OrganizationID
a.CreatedAt = existing.CreatedAt
a.UpdatedAt = now
if err := a.Update(ctx, conn, scope); err != nil {
return fmt.Errorf("cannot update asset: %w", err)
}
_, err := conn.Exec(ctx, `
DELETE FROM asset_vendors
WHERE tenant_id = $1 AND asset_id = $2
`, scope.GetTenantID(), a.ID)
if err != nil {
return fmt.Errorf("cannot delete asset vendors: %w", err)
}
if len(vendorIDs) > 0 {
for _, vendorID := range vendorIDs {
_, err := conn.Exec(ctx, `
INSERT INTO asset_vendors (tenant_id, asset_id, vendor_id, created_at)
VALUES ($1, $2, $3, $4)
`, scope.GetTenantID(), a.ID, vendorID, now)
if err != nil {
return fmt.Errorf("cannot insert asset vendor: %w", err)
}
}
}
return nil
}
// UpdateWithVendorsTx updates an asset and its vendor relationships in a single transaction
func (a *Asset) UpdateWithVendorsTx(
ctx context.Context,
db *pg.Client,
scope Scoper,
vendorIDs []gid.GID,
now time.Time,
) error {
return db.WithTx(ctx, func(conn pg.Conn) error {
return a.UpdateWithVendors(ctx, conn, scope, vendorIDs, now)
})
}

View File

@@ -0,0 +1,32 @@
// 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 AssetOrderField string
const (
AssetOrderFieldCreatedAt AssetOrderField = "CREATED_AT"
AssetOrderFieldAmount AssetOrderField = "AMOUNT"
AssetOrderFieldCriticity AssetOrderField = "CRITICITY"
AssetOrderFieldName AssetOrderField = "NAME"
)
func (p AssetOrderField) Column() string {
return string(p)
}
func (p AssetOrderField) String() string {
return string(p)
}

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 coredata
import (
"database/sql/driver"
"fmt"
)
type (
AssetType string
)
const (
AssetTypePhysical AssetType = "PHYSICAL"
AssetTypeVirtual AssetType = "VIRTUAL"
)
func (at AssetType) MarshalText() ([]byte, error) {
return []byte(at.String()), nil
}
func (at *AssetType) UnmarshalText(data []byte) error {
val := string(data)
switch val {
case AssetTypePhysical.String():
*at = AssetTypePhysical
case AssetTypeVirtual.String():
*at = AssetTypeVirtual
default:
return fmt.Errorf("invalid AssetType value: %q", val)
}
return nil
}
func (at AssetType) String() string {
return string(at)
}
func (at *AssetType) Scan(value any) error {
val, ok := value.(string)
if !ok {
return fmt.Errorf("invalid scan source for AssetType, expected string got %T", value)
}
return at.UnmarshalText([]byte(val))
}
func (at AssetType) Value() (driver.Value, error) {
return at.String(), nil
}

View File

@@ -0,0 +1,23 @@
// 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 CriticityLevel string
const (
CriticityLevelLow CriticityLevel = "LOW"
CriticityLevelMedium CriticityLevel = "MEDIUM"
CriticityLevelHigh CriticityLevel = "HIGH"
)

View File

@@ -33,4 +33,5 @@ const (
RiskEntityType
DocumentVersionEntityType
DocumentVersionSignatureEntityType
AssetEntityType
)

View File

@@ -0,0 +1,27 @@
-- Create enum types
CREATE TYPE criticity_level AS ENUM ('LOW', 'MEDIUM', 'HIGH');
CREATE TYPE asset_type AS ENUM ('PHYSICAL', 'VIRTUAL');
-- Create assets table
CREATE TABLE IF NOT EXISTS assets (
id TEXT PRIMARY KEY,
tenant_id TEXT NOT NULL,
name TEXT NOT NULL,
amount INTEGER NOT NULL,
owner_id TEXT NOT NULL REFERENCES peoples(id) ON UPDATE CASCADE ON DELETE CASCADE,
organization_id TEXT NOT NULL REFERENCES organizations(id) ON UPDATE CASCADE ON DELETE CASCADE,
criticity criticity_level DEFAULT 'MEDIUM',
asset_type asset_type NOT NULL DEFAULT 'VIRTUAL',
data_types_stored TEXT,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE NOT NULL
);
-- Create junction table for many-to-many relationship with vendors
CREATE TABLE IF NOT EXISTS asset_vendors (
asset_id TEXT REFERENCES assets(id) ON DELETE CASCADE,
vendor_id TEXT REFERENCES vendors(id) ON DELETE CASCADE,
tenant_id TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY (asset_id, vendor_id)
);

View File

@@ -29,6 +29,7 @@ import (
type (
Vendor struct {
ID gid.GID `db:"id"`
TenantID gid.TenantID `db:"tenant_id"`
OrganizationID gid.GID `db:"organization_id"`
Name string `db:"name"`
Description *string `db:"description"`
@@ -77,6 +78,7 @@ func (v *Vendor) LoadByID(
q := `
SELECT
id,
tenant_id,
organization_id,
name,
description,
@@ -243,6 +245,7 @@ func (v *Vendors) LoadByOrganizationID(
q := `
SELECT
id,
tenant_id,
organization_id,
name,
description,
@@ -386,3 +389,93 @@ func (v Vendor) ExpireNonExpiredRiskAssessments(
return nil
}
func (v *Vendors) LoadByAssetID(
ctx context.Context,
conn pg.Conn,
scope Scoper,
assetID gid.GID,
cursor *page.Cursor[VendorOrderField],
) error {
q := `
WITH vend AS (
SELECT
v.id,
v.tenant_id,
v.organization_id,
v.name,
v.description,
v.category,
v.headquarter_address,
v.legal_name,
v.website_url,
v.privacy_policy_url,
v.service_level_agreement_url,
v.data_processing_agreement_url,
v.business_associate_agreement_url,
v.subprocessors_list_url,
v.certifications,
v.business_owner_id,
v.security_owner_id,
v.status_page_url,
v.terms_of_service_url,
v.security_page_url,
v.trust_page_url,
v.created_at,
v.updated_at
FROM
vendors v
INNER JOIN
asset_vendors av ON v.id = av.vendor_id
WHERE
av.asset_id = @asset_id
)
SELECT
id,
tenant_id,
organization_id,
name,
description,
category,
headquarter_address,
legal_name,
website_url,
privacy_policy_url,
service_level_agreement_url,
data_processing_agreement_url,
business_associate_agreement_url,
subprocessors_list_url,
certifications,
business_owner_id,
security_owner_id,
status_page_url,
terms_of_service_url,
security_page_url,
trust_page_url,
created_at,
updated_at
FROM
vend
WHERE %s
AND %s
`
q = fmt.Sprintf(q, scope.SQLFragment(), cursor.SQLFragment())
args := pgx.NamedArgs{"asset_id": assetID}
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 vendors: %w", err)
}
vendors, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByName[Vendor])
if err != nil {
return fmt.Errorf("cannot collect vendors: %w", err)
}
*v = vendors
return nil
}

228
pkg/probo/asset_service.go Normal file
View File

@@ -0,0 +1,228 @@
package probo
import (
"context"
"fmt"
"time"
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/gid"
"github.com/getprobo/probo/pkg/page"
"go.gearno.de/kit/pg"
)
type AssetService struct {
svc *TenantService
}
type CreateAssetRequest struct {
OrganizationID gid.GID
Name string
Amount int
OwnerID gid.GID
Criticity coredata.CriticityLevel
AssetType coredata.AssetType
DataTypesStored string
VendorIDs []gid.GID
}
type UpdateAssetRequest struct {
ID gid.GID
Name *string
Amount *int
OwnerID *gid.GID
Criticity *coredata.CriticityLevel
AssetType *coredata.AssetType
DataTypesStored *string
VendorIDs []gid.GID
}
func (s AssetService) Get(
ctx context.Context,
assetID gid.GID,
) (*coredata.Asset, error) {
asset := &coredata.Asset{}
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return asset.LoadByID(ctx, conn, s.svc.scope, assetID)
},
)
if err != nil {
return nil, err
}
return asset, nil
}
func (s AssetService) GetByOwnerID(
ctx context.Context,
ownerID gid.GID,
) (*coredata.Asset, error) {
asset := &coredata.Asset{OwnerID: ownerID}
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return asset.LoadByOwnerID(ctx, conn, s.svc.scope)
},
)
if err != nil {
return nil, err
}
return asset, nil
}
func (s AssetService) ListForOrganizationID(
ctx context.Context,
organizationID gid.GID,
cursor *page.Cursor[coredata.AssetOrderField],
) (*page.Page[*coredata.Asset, coredata.AssetOrderField], error) {
var assets coredata.Assets
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return assets.LoadByOrganizationID(
ctx,
conn,
s.svc.scope,
organizationID,
cursor,
)
},
)
if err != nil {
return nil, err
}
return page.NewPage(assets, cursor), nil
}
func (s AssetService) Update(
ctx context.Context,
req UpdateAssetRequest,
) (*coredata.Asset, error) {
now := time.Now()
existing := &coredata.Asset{}
if err := s.svc.pg.WithConn(ctx, func(conn pg.Conn) error {
return existing.LoadByID(ctx, conn, s.svc.scope, req.ID)
}); err != nil {
return nil, fmt.Errorf("cannot load asset: %w", err)
}
asset := &coredata.Asset{
ID: req.ID,
OrganizationID: existing.OrganizationID,
Name: existing.Name,
Amount: existing.Amount,
OwnerID: existing.OwnerID,
Criticity: existing.Criticity,
AssetType: existing.AssetType,
DataTypesStored: existing.DataTypesStored,
CreatedAt: existing.CreatedAt,
UpdatedAt: now,
}
// Update fields from request
if req.Name != nil {
asset.Name = *req.Name
}
if req.Amount != nil {
asset.Amount = *req.Amount
}
if req.OwnerID != nil {
asset.OwnerID = *req.OwnerID
}
if req.Criticity != nil {
asset.Criticity = *req.Criticity
}
if req.AssetType != nil {
asset.AssetType = *req.AssetType
}
if req.DataTypesStored != nil {
asset.DataTypesStored = *req.DataTypesStored
}
if err := asset.UpdateWithVendorsTx(ctx, s.svc.pg, s.svc.scope, req.VendorIDs, now); err != nil {
return nil, err
}
return asset, nil
}
func (s AssetService) Create(
ctx context.Context,
req CreateAssetRequest,
) (*coredata.Asset, error) {
now := time.Now()
assetID := gid.New(s.svc.scope.GetTenantID(), coredata.AssetEntityType)
organization := &coredata.Organization{}
asset := &coredata.Asset{
ID: assetID,
OrganizationID: req.OrganizationID,
Name: req.Name,
Amount: req.Amount,
OwnerID: req.OwnerID,
Criticity: req.Criticity,
AssetType: req.AssetType,
DataTypesStored: req.DataTypesStored,
CreatedAt: now,
UpdatedAt: now,
}
err := s.svc.pg.WithTx(
ctx,
func(conn pg.Conn) error {
return asset.CreateWithVendors(ctx, conn, s.svc.scope, organization, req.VendorIDs, now)
},
)
if err != nil {
return nil, err
}
return asset, nil
}
func (s AssetService) Delete(
ctx context.Context,
assetID gid.GID,
) error {
asset := &coredata.Asset{ID: assetID}
return s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return asset.Delete(ctx, conn, s.svc.scope)
},
)
}
func (s AssetService) ListVendors(
ctx context.Context,
assetID gid.GID,
cursor *page.Cursor[coredata.VendorOrderField],
) (*page.Page[*coredata.Vendor, coredata.VendorOrderField], error) {
var vendors coredata.Vendors
err := s.svc.pg.WithConn(
ctx,
func(conn pg.Conn) error {
return vendors.LoadByAssetID(ctx, conn, s.svc.scope, assetID, cursor)
},
)
if err != nil {
return nil, err
}
return page.NewPage(vendors, cursor), nil
}

View File

@@ -59,6 +59,7 @@ type (
Risks *RiskService
VendorComplianceReports *VendorComplianceReportService
Connectors *ConnectorService
Assets *AssetService
}
)
@@ -129,5 +130,6 @@ func (s *Service) WithTenant(tenantID gid.TenantID) *TenantService {
tenantService.Risks = &RiskService{svc: tenantService}
tenantService.VendorComplianceReports = &VendorComplianceReportService{svc: tenantService}
tenantService.Connectors = &ConnectorService{svc: tenantService}
tenantService.Assets = &AssetService{svc: tenantService}
return tenantService
}

View File

@@ -343,6 +343,23 @@ enum DocumentType @goModel(model: "github.com/getprobo/probo/pkg/coredata.Docume
POLICY @goEnum(value: "github.com/getprobo/probo/pkg/coredata.DocumentTypePolicy")
}
enum AssetType @goModel(model: "github.com/getprobo/probo/pkg/coredata.AssetType") {
PHYSICAL @goEnum(value: "github.com/getprobo/probo/pkg/coredata.AssetTypePhysical")
VIRTUAL @goEnum(value: "github.com/getprobo/probo/pkg/coredata.AssetTypeVirtual")
}
enum CriticityLevel @goModel(model: "github.com/getprobo/probo/pkg/coredata.CriticityLevel") {
LOW @goEnum(value: "github.com/getprobo/probo/pkg/coredata.CriticityLevelLow")
MEDIUM @goEnum(value: "github.com/getprobo/probo/pkg/coredata.CriticityLevelMedium")
HIGH @goEnum(value: "github.com/getprobo/probo/pkg/coredata.CriticityLevelHigh")
}
enum AssetOrderField @goModel(model: "github.com/getprobo/probo/pkg/coredata.AssetOrderField") {
CREATED_AT @goEnum(value: "github.com/getprobo/probo/pkg/coredata.AssetOrderFieldCreatedAt")
AMOUNT @goEnum(value: "github.com/getprobo/probo/pkg/coredata.AssetOrderFieldAmount")
CRITICITY @goEnum(value: "github.com/getprobo/probo/pkg/coredata.AssetOrderFieldCriticity")
}
# Order Input Types
input UserOrder
@goModel(
@@ -532,6 +549,14 @@ type Organization implements Node {
orderBy: TaskOrder
): TaskConnection! @goField(forceResolver: true)
assets(
first: Int
after: CursorKey
last: Int
before: CursorKey
orderBy: AssetOrder
): AssetConnection! @goField(forceResolver: true)
createdAt: Datetime!
updatedAt: Datetime!
}
@@ -1126,6 +1151,12 @@ type Mutation {
exportAudit(input: ExportAuditInput!): ExportAuditPayload!
assessVendor(input: AssessVendorInput!): AssessVendorPayload!
createAsset(input: CreateAssetInput!): CreateAssetPayload!
updateAsset(input: UpdateAssetInput!): UpdateAssetPayload!
deleteAsset(input: DeleteAssetInput!): DeleteAssetPayload!
addAssetVendor(input: AddAssetVendorInput!): AddAssetVendorPayload!
removeAssetVendor(input: RemoveAssetVendorInput!): RemoveAssetVendorPayload!
}
# Input Types
@@ -1832,3 +1863,94 @@ input AssessVendorInput {
type AssessVendorPayload {
vendor: Vendor!
}
type Asset implements Node {
id: ID!
name: String!
amount: Int!
owner: People! @goField(forceResolver: true)
vendors(
first: Int
after: CursorKey
last: Int
before: CursorKey
orderBy: VendorOrder
): VendorConnection! @goField(forceResolver: true)
criticity: CriticityLevel!
assetType: AssetType! @goField(forceResolver: true)
dataTypesStored: String!
organization: Organization! @goField(forceResolver: true)
createdAt: Datetime!
updatedAt: Datetime!
}
type AssetConnection {
edges: [AssetEdge!]!
pageInfo: PageInfo!
}
type AssetEdge {
cursor: CursorKey!
node: Asset!
}
input AssetOrder {
direction: OrderDirection!
field: AssetOrderField!
}
input CreateAssetInput {
organizationId: ID!
name: String!
amount: Int!
ownerId: ID!
criticity: CriticityLevel! = MEDIUM
assetType: AssetType!
dataTypesStored: String!
vendorIds: [ID!]
}
input UpdateAssetInput {
id: ID!
name: String
amount: Int
ownerId: ID
criticity: CriticityLevel
assetType: AssetType
dataTypesStored: String
vendorIds: [ID!]
}
input DeleteAssetInput {
assetId: ID!
}
input AddAssetVendorInput {
assetId: ID!
vendorId: ID!
}
input RemoveAssetVendorInput {
assetId: ID!
vendorId: ID!
}
type CreateAssetPayload {
assetEdge: AssetEdge!
}
type UpdateAssetPayload {
asset: Asset!
}
type DeleteAssetPayload {
deletedAssetId: ID!
}
type AddAssetVendorPayload {
asset: Asset!
}
type RemoveAssetVendorPayload {
asset: Asset!
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,38 @@
package types
import (
"github.com/getprobo/probo/pkg/coredata"
"github.com/getprobo/probo/pkg/page"
)
func NewAsset(asset *coredata.Asset) *Asset {
return &Asset{
ID: asset.ID,
Name: asset.Name,
Amount: asset.Amount,
Criticity: asset.Criticity,
AssetType: asset.AssetType,
DataTypesStored: asset.DataTypesStored,
CreatedAt: asset.CreatedAt,
UpdatedAt: asset.UpdatedAt,
}
}
func NewAssetEdge(asset *coredata.Asset, orderField coredata.AssetOrderField) *AssetEdge {
return &AssetEdge{
Node: NewAsset(asset),
Cursor: asset.CursorKey(orderField),
}
}
func NewAssetConnection(page *page.Page[*coredata.Asset, coredata.AssetOrderField]) *AssetConnection {
edges := make([]*AssetEdge, len(page.Data))
for i, asset := range page.Data {
edges[i] = NewAssetEdge(asset, page.Cursor.OrderBy.Field)
}
return &AssetConnection{
Edges: edges,
PageInfo: NewPageInfo(page),
}
}

View File

@@ -20,6 +20,15 @@ type Node interface {
GetID() gid.GID
}
type AddAssetVendorInput struct {
AssetID gid.GID `json:"assetId"`
VendorID gid.GID `json:"vendorId"`
}
type AddAssetVendorPayload struct {
Asset *Asset `json:"asset"`
}
type AssessVendorInput struct {
ID gid.GID `json:"id"`
WebsiteURL string `json:"websiteUrl"`
@@ -29,6 +38,38 @@ type AssessVendorPayload struct {
Vendor *Vendor `json:"vendor"`
}
type Asset struct {
ID gid.GID `json:"id"`
Name string `json:"name"`
Amount int `json:"amount"`
Owner *People `json:"owner"`
Vendors *VendorConnection `json:"vendors"`
Criticity coredata.CriticityLevel `json:"criticity"`
AssetType coredata.AssetType `json:"assetType"`
DataTypesStored string `json:"dataTypesStored"`
Organization *Organization `json:"organization"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
func (Asset) IsNode() {}
func (this Asset) GetID() gid.GID { return this.ID }
type AssetConnection struct {
Edges []*AssetEdge `json:"edges"`
PageInfo *PageInfo `json:"pageInfo"`
}
type AssetEdge struct {
Cursor page.CursorKey `json:"cursor"`
Node *Asset `json:"node"`
}
type AssetOrder struct {
Direction page.OrderDirection `json:"direction"`
Field coredata.AssetOrderField `json:"field"`
}
type AssignTaskInput struct {
TaskID gid.GID `json:"taskId"`
AssignedToID gid.GID `json:"assignedToId"`
@@ -97,6 +138,21 @@ type ControlEdge struct {
Node *Control `json:"node"`
}
type CreateAssetInput struct {
OrganizationID gid.GID `json:"organizationId"`
Name string `json:"name"`
Amount int `json:"amount"`
OwnerID gid.GID `json:"ownerId"`
Criticity coredata.CriticityLevel `json:"criticity"`
AssetType coredata.AssetType `json:"assetType"`
DataTypesStored string `json:"dataTypesStored"`
VendorIds []gid.GID `json:"vendorIds,omitempty"`
}
type CreateAssetPayload struct {
AssetEdge *AssetEdge `json:"assetEdge"`
}
type CreateControlDocumentMappingInput struct {
ControlID gid.GID `json:"controlId"`
DocumentID gid.GID `json:"documentId"`
@@ -285,6 +341,14 @@ type CreateVendorRiskAssessmentPayload struct {
VendorRiskAssessmentEdge *VendorRiskAssessmentEdge `json:"vendorRiskAssessmentEdge"`
}
type DeleteAssetInput struct {
AssetID gid.GID `json:"assetId"`
}
type DeleteAssetPayload struct {
DeletedAssetID gid.GID `json:"deletedAssetId"`
}
type DeleteControlDocumentMappingInput struct {
ControlID gid.GID `json:"controlId"`
DocumentID gid.GID `json:"documentId"`
@@ -635,6 +699,7 @@ type Organization struct {
Measures *MeasureConnection `json:"measures"`
Risks *RiskConnection `json:"risks"`
Tasks *TaskConnection `json:"tasks"`
Assets *AssetConnection `json:"assets"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
@@ -702,6 +767,15 @@ type PublishDocumentVersionPayload struct {
type Query struct {
}
type RemoveAssetVendorInput struct {
AssetID gid.GID `json:"assetId"`
VendorID gid.GID `json:"vendorId"`
}
type RemoveAssetVendorPayload struct {
Asset *Asset `json:"asset"`
}
type RemoveUserInput struct {
OrganizationID gid.GID `json:"organizationId"`
UserID gid.GID `json:"userId"`
@@ -814,6 +888,21 @@ type UnassignTaskPayload struct {
Task *Task `json:"task"`
}
type UpdateAssetInput struct {
ID gid.GID `json:"id"`
Name *string `json:"name,omitempty"`
Amount *int `json:"amount,omitempty"`
OwnerID *gid.GID `json:"ownerId,omitempty"`
Criticity *coredata.CriticityLevel `json:"criticity,omitempty"`
AssetType *coredata.AssetType `json:"assetType,omitempty"`
DataTypesStored *string `json:"dataTypesStored,omitempty"`
VendorIds []gid.GID `json:"vendorIds,omitempty"`
}
type UpdateAssetPayload struct {
Asset *Asset `json:"asset"`
}
type UpdateDocumentInput struct {
ID gid.GID `json:"id"`
Title *string `json:"title,omitempty"`

View File

@@ -20,6 +20,65 @@ import (
"github.com/vektah/gqlparser/v2/gqlerror"
)
// Owner is the resolver for the owner field.
func (r *assetResolver) Owner(ctx context.Context, obj *types.Asset) (*types.People, error) {
svc := GetTenantService(ctx, r.proboSvc, obj.ID.TenantID())
asset, err := svc.Assets.Get(ctx, obj.ID)
if err != nil {
panic(fmt.Errorf("cannot get asset: %w", err))
}
owner, err := svc.Peoples.Get(ctx, asset.OwnerID)
if err != nil {
panic(fmt.Errorf("cannot get owner: %w", err))
}
return types.NewPeople(owner), nil
}
// Vendors is the resolver for the vendors field.
func (r *assetResolver) Vendors(ctx context.Context, obj *types.Asset, first *int, after *page.CursorKey, last *int, before *page.CursorKey, orderBy *types.VendorOrderBy) (*types.VendorConnection, error) {
svc := GetTenantService(ctx, r.proboSvc, obj.ID.TenantID())
pageOrderBy := page.OrderBy[coredata.VendorOrderField]{
Field: coredata.VendorOrderFieldCreatedAt,
Direction: page.OrderDirectionDesc,
}
if orderBy != nil {
pageOrderBy = page.OrderBy[coredata.VendorOrderField]{
Field: orderBy.Field,
Direction: orderBy.Direction,
}
}
cursor := types.NewCursor(first, after, last, before, pageOrderBy)
page, err := svc.Assets.ListVendors(ctx, obj.ID, cursor)
if err != nil {
panic(fmt.Errorf("cannot list asset vendors: %w", err))
}
return types.NewVendorConnection(page), nil
}
// AssetType is the resolver for the assetType field.
func (r *assetResolver) AssetType(ctx context.Context, obj *types.Asset) (coredata.AssetType, error) {
svc := GetTenantService(ctx, r.proboSvc, obj.ID.TenantID())
asset, err := svc.Assets.Get(ctx, obj.ID)
if err != nil {
panic(fmt.Errorf("cannot get asset: %w", err))
}
return asset.AssetType, nil
}
// Organization is the resolver for the organization field.
func (r *assetResolver) Organization(ctx context.Context, obj *types.Asset) (*types.Organization, error) {
panic(fmt.Errorf("not implemented: Organization - organization"))
}
// Framework is the resolver for the framework field.
func (r *controlResolver) Framework(ctx context.Context, obj *types.Control) (*types.Framework, error) {
svc := GetTenantService(ctx, r.proboSvc, obj.ID.TenantID())
@@ -1557,6 +1616,77 @@ func (r *mutationResolver) AssessVendor(ctx context.Context, input types.AssessV
}, nil
}
// CreateAsset is the resolver for the createAsset field.
func (r *mutationResolver) CreateAsset(ctx context.Context, input types.CreateAssetInput) (*types.CreateAssetPayload, error) {
svc := GetTenantService(ctx, r.proboSvc, input.OrganizationID.TenantID())
asset, err := svc.Assets.Create(ctx, probo.CreateAssetRequest{
OrganizationID: input.OrganizationID,
Name: input.Name,
Amount: input.Amount,
OwnerID: input.OwnerID,
Criticity: input.Criticity,
AssetType: input.AssetType,
DataTypesStored: input.DataTypesStored,
VendorIDs: input.VendorIds,
})
if err != nil {
return nil, fmt.Errorf("cannot create asset: %w", err)
}
return &types.CreateAssetPayload{
AssetEdge: types.NewAssetEdge(asset, coredata.AssetOrderFieldCreatedAt),
}, nil
}
// UpdateAsset is the resolver for the updateAsset field.
func (r *mutationResolver) UpdateAsset(ctx context.Context, input types.UpdateAssetInput) (*types.UpdateAssetPayload, error) {
svc := GetTenantService(ctx, r.proboSvc, input.ID.TenantID())
asset, err := svc.Assets.Update(ctx, probo.UpdateAssetRequest{
ID: input.ID,
Name: input.Name,
Amount: input.Amount,
OwnerID: input.OwnerID,
Criticity: input.Criticity,
AssetType: input.AssetType,
DataTypesStored: input.DataTypesStored,
VendorIDs: input.VendorIds,
})
if err != nil {
return nil, fmt.Errorf("cannot update asset: %w", err)
}
return &types.UpdateAssetPayload{
Asset: types.NewAsset(asset),
}, nil
}
// DeleteAsset is the resolver for the deleteAsset field.
func (r *mutationResolver) DeleteAsset(ctx context.Context, input types.DeleteAssetInput) (*types.DeleteAssetPayload, error) {
svc := GetTenantService(ctx, r.proboSvc, input.AssetID.TenantID())
err := svc.Assets.Delete(ctx, input.AssetID)
if err != nil {
return nil, fmt.Errorf("cannot delete asset: %w", err)
}
return &types.DeleteAssetPayload{
DeletedAssetID: input.AssetID,
}, nil
}
// AddAssetVendor is the resolver for the addAssetVendor field.
func (r *mutationResolver) AddAssetVendor(ctx context.Context, input types.AddAssetVendorInput) (*types.AddAssetVendorPayload, error) {
panic(fmt.Errorf("not implemented: AddAssetVendor - addAssetVendor"))
}
// RemoveAssetVendor is the resolver for the removeAssetVendor field.
func (r *mutationResolver) RemoveAssetVendor(ctx context.Context, input types.RemoveAssetVendorInput) (*types.RemoveAssetVendorPayload, error) {
panic(fmt.Errorf("not implemented: RemoveAssetVendor - removeAssetVendor"))
}
// LogoURL is the resolver for the logoUrl field.
func (r *organizationResolver) LogoURL(ctx context.Context, obj *types.Organization) (*string, error) {
svc := GetTenantService(ctx, r.proboSvc, obj.ID.TenantID())
@@ -1787,6 +1917,31 @@ func (r *organizationResolver) Tasks(ctx context.Context, obj *types.Organizatio
return types.NewTaskConnection(page), nil
}
// Assets is the resolver for the assets field.
func (r *organizationResolver) Assets(ctx context.Context, obj *types.Organization, first *int, after *page.CursorKey, last *int, before *page.CursorKey, orderBy *types.AssetOrder) (*types.AssetConnection, error) {
svc := GetTenantService(ctx, r.proboSvc, obj.ID.TenantID())
pageOrderBy := page.OrderBy[coredata.AssetOrderField]{
Field: coredata.AssetOrderFieldCreatedAt,
Direction: page.OrderDirectionDesc,
}
if orderBy != nil {
pageOrderBy = page.OrderBy[coredata.AssetOrderField]{
Field: orderBy.Field,
Direction: orderBy.Direction,
}
}
cursor := types.NewCursor(first, after, last, before, pageOrderBy)
page, err := svc.Assets.ListForOrganizationID(ctx, obj.ID, cursor)
if err != nil {
panic(fmt.Errorf("cannot list organization assets: %w", err))
}
return types.NewAssetConnection(page), nil
}
// Node is the resolver for the node field.
func (r *queryResolver) Node(ctx context.Context, id gid.GID) (types.Node, error) {
svc := GetTenantService(ctx, r.proboSvc, id.TenantID())
@@ -1878,6 +2033,12 @@ func (r *queryResolver) Node(ctx context.Context, id gid.GID) (types.Node, error
panic(fmt.Errorf("cannot get document version signature: %w", err))
}
return types.NewDocumentVersionSignature(documentVersionSignature), nil
case coredata.AssetEntityType:
asset, err := svc.Assets.Get(ctx, id)
if err != nil {
panic(fmt.Errorf("cannot get asset: %w", err))
}
return types.NewAsset(asset), nil
default:
}
@@ -2190,7 +2351,6 @@ func (r *vendorResolver) BusinessOwner(ctx context.Context, obj *types.Vendor) (
// SecurityOwner is the resolver for the securityOwner field.
func (r *vendorResolver) SecurityOwner(ctx context.Context, obj *types.Vendor) (*types.People, error) {
svc := GetTenantService(ctx, r.proboSvc, obj.ID.TenantID())
vendor, err := svc.Vendors.Get(ctx, obj.ID)
if err != nil {
panic(fmt.Errorf("failed to get vendor: %w", err))
@@ -2286,6 +2446,9 @@ func (r *viewerResolver) Organizations(ctx context.Context, obj *types.Viewer, f
}, nil
}
// Asset returns schema.AssetResolver implementation.
func (r *Resolver) Asset() schema.AssetResolver { return &assetResolver{r} }
// Control returns schema.ControlResolver implementation.
func (r *Resolver) Control() schema.ControlResolver { return &controlResolver{r} }
@@ -2345,6 +2508,7 @@ func (r *Resolver) VendorRiskAssessment() schema.VendorRiskAssessmentResolver {
// Viewer returns schema.ViewerResolver implementation.
func (r *Resolver) Viewer() schema.ViewerResolver { return &viewerResolver{r} }
type assetResolver struct{ *Resolver }
type controlResolver struct{ *Resolver }
type documentResolver struct{ *Resolver }
type documentVersionResolver struct{ *Resolver }