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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cterasdk/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
'messaging',
'portals',
'query',
'quotas',
'remote',
'reports',
'servers',
Expand Down
4 changes: 2 additions & 2 deletions cterasdk/core/cloudfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from .base_command import BaseCommand
from . import query, devices
from .enum import ListFilter, PolicyType
from .enum import ListFilter, PolicyType, QuotaValue
from .types import ArchiveSettingsBuilder, ComplianceSettingsBuilder, ExtendedAttributesBuilder, DevicesDelta, FoldersDelta
from ..common import union, Object
from ..exceptions import CTERAException, ObjectNotFoundException
Expand Down Expand Up @@ -283,7 +283,7 @@ def modify(self, current_name, owner, new_name=None, # pylint: disable=too-many
if winacls:
param.enableSyncWinNtExtendedAttributes = winacls
if quota:
param.folderQuota = quota
param.folderQuota = None if quota == QuotaValue.Unlimited else quota
if archive_settings:
param.archiveSettings = archive_settings
if compliance_settings:
Expand Down
9 changes: 9 additions & 0 deletions cterasdk/core/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,3 +795,12 @@ class KRBSecurity:
KRB5 = "krb5"
KRB5I = "krb5i"
KRB5P = "krb5p"


class QuotaValue:
"""
Quota Value

:ivar str Unlimited: Unlimited
"""
Unlimited = 'Unlimited'
21 changes: 10 additions & 11 deletions cterasdk/core/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ def execute(core, path, name, param):
return Command(execute if name else database, core, path, name or 'query')


def v2_callback_function(core, path):
def v2_callback_function(core, path, *, callback_response=None):

def wrapper(core, path, params):
return v2DefaultResponse(core.clients.v2.get(path, params=dict(params)))
return callback_response(core.clients.v2.get(path, params=dict(params)))

return Command(wrapper, core, path)

Expand All @@ -53,16 +53,15 @@ def iterator(core, path, param=None, name=None, *, callback_response=None, versi

:returns: Query iterator object
"""

if version != 'v2':

callback_response = callback_response if callback_response else DefaultResponse

if version == 'v2':
callback_response = callback_response or v2DefaultResponse
callback_function = v2_callback_function(core, path, callback_response=callback_response)
params = v2QueryParams(**(param or {}))
else:
callback_response = callback_response or DefaultResponse
callback_function = v1_callback_function(core, path, name, callback_response=callback_response)

return QueryIterator(callback_function, param if param else QueryParams())

return QueryIterator(v2_callback_function(core, path), v2QueryParams(**param))
params = param or QueryParams()
return QueryIterator(callback_function, params)


class Restriction:
Expand Down
135 changes: 135 additions & 0 deletions cterasdk/core/quotas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import logging

from .base_command import BaseCommand
from .enum import QuotaValue
from . import query
from .types import PortalAccount, QuotaRule
from ..common import union, parse_base_object_ref
from ..lib import SubfoldersQuotaResponse


logger = logging.getLogger('cterasdk.core')


class Quotas(BaseCommand):
"""
CTERA Portal Quota Management APIs

:ivar cterasdk.core.quotas.CloudDrives drives: Management of Cloud Drive Folder Quotas
:ivar cterasdk.core.quotas.Subfolders subfolders: Management of subfolder Quotas
"""

def __init__(self, portal):
super().__init__(portal)
self.drives = CloudDrives(self._core)
self.subfolders = Subfolders(self._core)


class CloudDrives(BaseCommand):

default = ['uid', 'name', 'owner', 'folderQuota', 'isDeleted', 'folderStats']

def all(self, include=None):
"""
List Cloud Drive Folder Quota Rules.

:param list[str] include: Optional list of Cloud Drive Folder attributes to include.
:returns: A list of quota rules.
:rtype: list[cterasdk.core.types.QuotaRule]
"""
include = union(include or [], CloudDrives.default)
param = query.QueryParamBuilder().include(include).orFilter(False).addFilter(
query.FilterBuilder('folderQuota').gt(-1)
).build()
for drive in query.iterator(self._core, '/cloudDrives', param):
yield QuotaRule(
drive.uid,
drive.name,
PortalAccount.from_base_object_ref(drive.owner),
drive.folderQuota << 10,
drive.folderStats.cloudFolderSize >> 20,
True,
drive.isDeleted
)

def add(self, name, owner, quota):
"""
Add Cloud Drive Folder Quota Rule

:param str name: Cloud Drive Folder name
:param cterasdk.core.types.UserAccount owner: User account, the owner of the folder
:param int quota: Quota in GB
"""
response = self._core.cloudfs.drives.modify(name, owner, quota=quota)
logger.info("Quota rule added for Cloud Drive Folder '%s' and owner '%s'", name, str(owner))
return response

def remove(self, name, owner):
"""
Remove Cloud Drive Folder Quota

:param str name: Cloud Drive Folder name
:param cterasdk.core.types.UserAccount owner: User account, the owner of the folder
"""
self._core.cloudfs.drives.modify(name, owner, quota=QuotaValue.Unlimited)
logger.info("Quota rule removed for Cloud Drive Folder '%s' and owner '%s'", name, str(owner))


class Subfolders(BaseCommand):

def all(self):
"""
List Subfolder Quota Rules.

:returns: A list of quota rules.
:rtype: list[cterasdk.core.types.QuotaRule]
"""
for rule in query.iterator(self._core, f'portals/{self._core.session().account.tenant}/subfolder-quotas',
callback_response=SubfoldersQuotaResponse, version='v2'):
yield QuotaRule(
rule.cloud_drive_id,
f'{rule.cloud_drive.name}{rule.subfolder_path}',
PortalAccount.from_base_object_ref(rule.cloud_drive.owner.ref),
rule.quota_mb,
None,
rule.should_enforce,
False
)

def add(self, path, owner, quota, enforce):
"""
Add Subfolder Quota Rule

:param str path: Path
:param cterasdk.core.types.UserAccount owner: User account, the owner of the folder
:param int quota: Quota in MB
"""
parts = path.lstrip('/').split('/')
drive = self._core.cloudfs.drives.find(parts[0], owner, include=['uid', 'owner'])
param = {
'cloudDriveId': drive.uid,
'subfolderPath': f"/{'/'.join(parts[1:])}",
'ownerId': parse_base_object_ref(drive.owner).uid,
'quotaMb': quota,
'shouldEnforce': enforce
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add payload uses camelCase keys

High Severity

Subfolders.add sends camelCase fields such as cloudDriveId and quotaMb. The same v2 resource is read with snake_case (cloud_drive_id, quota_mb), and other v2 writes in this SDK (for example shares) also use snake_case. The server is likely to ignore or reject the body, so creates silently fail or persist empty values.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit fb394a4. Configure here.

response = self._core.clients.v2.post('portals/cterademo-saimon/subfolder-quotas', param)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hardcoded demo tenant in add

High Severity

Subfolders.add posts to portals/cterademo-saimon/subfolder-quotas instead of the session tenant used by all and remove. Every create goes to that demo portal, so quota rules are never created in the caller’s tenant.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit fb394a4. Configure here.

logger.info("Quota rule added for path '%s' and owner '%s'", path, str(PortalAccount.from_base_object_ref(drive.owner)))
return response

def remove(self, path, owner):
"""
Remove Subfolder Folder Quota

:param str path: Path
:param cterasdk.core.types.UserAccount owner: User account, the owner of the folder
"""
path = f"{path.rstrip('/')}/"
for rule in self.all():
if path == rule.path and rule.owner == owner:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove path comparison never matches

High Severity

Subfolders.remove appends a trailing slash to the caller path, then compares it to rule.path. all() builds that path as name + subfolder_path with no trailing slash, and add() stores the subfolder the same way. The equality check therefore fails for documented paths, so deletes log “not found” and leave the rule in place.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit fb394a4. Configure here.

self._core.clients.v2.delete(f'portals/{self._core.session().account.tenant}/subfolder-quotas/{rule.volume}', params={
'path': "/" + path.partition("/")[2]
})
logger.info("Quota rule removed for path '%s' and owner '%s'", rule.path, str(rule.owner))
return
logger.info("Quota rule not found for path '%s' and owner '%s'", path, str(owner))
48 changes: 47 additions & 1 deletion cterasdk/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from abc import ABC
from datetime import datetime
from collections import namedtuple
from ..common import DateTimeUtils, StringCriteriaBuilder, PredefinedListCriteriaBuilder, CustomListCriteriaBuilder, Object
from ..common import DateTimeUtils, StringCriteriaBuilder, PredefinedListCriteriaBuilder, CustomListCriteriaBuilder, Object, \
parse_base_object_ref
from ..lib.storage import commonfs

from .enum import PortalAccountType, CollaboratorType, FileAccessMode, PlanCriteria, TemplateCriteria, ProtectionLevel, \
Expand Down Expand Up @@ -79,6 +80,15 @@ def from_collaborator(collaborator):
return GroupAccount(collaborator.name, collaborator.domain)
return None

@staticmethod
def from_base_object_ref(ref):
r = parse_base_object_ref(ref)
if r.classname == 'ADUser':
return UserAccount(r.name, r.more)
if r.classname == 'PortalUser':
return UserAccount(r.name)
raise ValueError(f"Invalid account type: '{r.classname}'. Expected 'ADUser', or 'PortalUser'")

def __eq__(self, other):
if type(self) is type(other):
if self.account_type == other.account_type and self.name == other.name and self.directory == other.directory:
Expand All @@ -89,6 +99,9 @@ def __eq__(self, other):
def upn(self):
return f'{self.name}@{self.directory}' if self.directory else self.name

def __repr__(self):
return self.upn

def __str__(self):
return (self.directory if self.directory else '') + '\\' + self.name

Expand Down Expand Up @@ -1299,3 +1312,36 @@ def __init__(self):
added=[],
removed=[]
)


class QuotaRule:
"""
Quota Rule

:ivar int volume: Cloud Drive Folder ID
:ivar str path: Path
:ivar cterasdk.core.types.UserAccount owner: Cloud Drive Folder Owner
:ivar int limit_mb: Quota limit in megabytes
:ivar int usage_mb: Current usage in megabytes
:ivar bool enforce: Quota enforcement enabled
:ivar bool deleted: Target folder is deleted
"""
def __init__(self, volume, path, owner, limit_mb, usage_mb, enforce, deleted):
self.volume = volume
self.path = path
self.owner = owner
self.limit_mb = limit_mb
self.usage_mb = usage_mb
self.enforce = enforce
self.deleted = deleted

def __repr__(self):
return (
f'{self.__class__.__name__}('
f'path={self.path}, '
f'owner={self.owner!r}, '
f'megabytes={self.limit_mb}, '
f'usage={self.usage_mb}, '
f'enforce={self.enforce}, '
f'deleted={self.deleted})'
)
1 change: 1 addition & 0 deletions cterasdk/edge/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
'ntp',
'power',
'query',
'quotas',
'remote',
'rsync',
'ransom_protect',
Expand Down
33 changes: 33 additions & 0 deletions cterasdk/edge/quotas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import logging

from . import query
from .base_command import BaseCommand
from ..lib import QuotaResponse
from .types import QuotaRule


logger = logging.getLogger('cterasdk.edge')


class Quotas(BaseCommand):
"""
Edge Filer Quota Management APIs
"""

def all(self):
"""
List Cloud Drive Folder Quota Rules.

:returns: A list of quota rules.
:rtype: list[cterasdk.edge.types.QuotaRule]
"""
param = query.QueryParamBuilder().countLimit(150).build()
for rule in query.iterator(self._edge, '/config/cloudsync', param, 'localquotadb_getQuotaState', QuotaResponse):
policy = rule.quotaEntity
yield QuotaRule(
f'{policy.folderName}/{policy.relPath}' if policy.relPath else policy.folderName,
policy.ownerName,
policy.localUsage,
-1 if not policy.relPath else policy.cloudRemaining >> 20,
policy.enforceQuota
)
28 changes: 28 additions & 0 deletions cterasdk/edge/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,3 +441,31 @@ class NetworkInterface(Object):
"""
def __init__(self, port, name, mac):
super().__init__(port=port, name=name, mac=mac)


class QuotaRule:
"""
Quota Rule

:ivar str path: Path
:ivar str owner: Owner
:ivar int usage_mb: Current usage in megabytes
:ivar int free_mb: Free space in megabytes
:ivar bool enforce: Quota enforcement enabled
"""
def __init__(self, path, owner, usage_mb, free_mb, enforce):
self.path = path
self.owner = owner
self.usage_mb = usage_mb
self.free_mb = free_mb
self.enforce = enforce

def __repr__(self):
return (
f'{self.__class__.__name__}('
f'path={self.path}, '
f'owner={self.owner}, '
f'usage={self.usage_mb}, '
f'free={self.free_mb}, '
f'enforce={self.enforce})'
)
3 changes: 2 additions & 1 deletion cterasdk/lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from .consent import ask # noqa: E402, F401
from .tempfile import TempfileServices # noqa: E402, F401
from .iterator import QueryIterator, BaseResponse, \
DefaultResponse, v2DefaultResponse, KeyValueQueryIterator, QueryLogsResponse, CursorResponse # noqa: E402, F401
DefaultResponse, v2DefaultResponse, KeyValueQueryIterator, QueryLogsResponse, CursorResponse, \
SubfoldersQuotaResponse, QuotaResponse # noqa: E402, F401
from .tracker import track, ErrorStatus # noqa: E402, F401
from .crypto import CryptoServices, X509Certificate, PrivateKey, create_certificate_chain # noqa: E402, F401
19 changes: 19 additions & 0 deletions cterasdk/lib/iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,25 @@ def objects(self):
return self._response.data.items


class SubfoldersQuotaResponse(BaseResponse):

@property
def more(self):
return not self._response.data.last

@property
@abstractmethod
def objects(self):
return self._response.data.content


class QuotaResponse(DefaultResponse):

@property
def objects(self):
return self._response.entitiesQuota


class QueryLogsResponse(DefaultResponse):

@property
Expand Down
Loading
Loading