19
19
import logging
20
20
import os
21
21
import pathlib
22
+ import stat
22
23
import typing
24
+ from typing import Optional
23
25
24
26
import httpx
25
27
import jwt
26
28
27
29
from . import http
28
30
from .constants import ENV_API_KEY , PLANET_BASE_URL , SECRET_FILE_PATH
29
31
from .exceptions import AuthException
30
- from typing import Optional
31
32
32
33
LOGGER = logging .getLogger (__name__ )
33
34
@@ -226,8 +227,15 @@ def value(self):
226
227
227
228
class _SecretFile :
228
229
229
- def __init__ (self , path ):
230
- self .path = path
230
+ def __init__ (self , path : typing .Union [str , pathlib .Path ]):
231
+ self .path = pathlib .Path (path )
232
+
233
+ self .permissions = stat .S_IRUSR | stat .S_IWUSR # user rw
234
+
235
+ # in sdk versions <=2.0.0, secret file was created with the wrong
236
+ # permissions, fix this automatically as well as catching the unlikely
237
+ # cases where the permissions get changed externally
238
+ self ._enforce_permissions ()
231
239
232
240
def write (self , contents : dict ):
233
241
try :
@@ -240,11 +248,29 @@ def write(self, contents: dict):
240
248
241
249
def _write (self , contents : dict ):
242
250
LOGGER .debug (f'Writing to { self .path } ' )
243
- with open (self .path , 'w' ) as fp :
251
+
252
+ def opener (path , flags ):
253
+ return os .open (path , flags , self .permissions )
254
+
255
+ with open (self .path , 'w' , opener = opener ) as fp :
244
256
fp .write (json .dumps (contents ))
245
257
246
258
def read (self ) -> dict :
247
259
LOGGER .debug (f'Reading from { self .path } ' )
248
260
with open (self .path , 'r' ) as fp :
249
261
contents = json .loads (fp .read ())
250
262
return contents
263
+
264
+ def _enforce_permissions (self ):
265
+ '''if the file's permissions are not what they should be, fix them'''
266
+ try :
267
+ # in octal, permissions is the last three bits of the mode
268
+ file_permissions = self .path .stat ().st_mode & 0o777
269
+ if file_permissions != self .permissions :
270
+ LOGGER .debug (
271
+ f'{ self .path } permissions are { oct (file_permissions )} , '
272
+ f'should be { oct (self .permissions )} . Fixing.' )
273
+ self .path .chmod (self .permissions )
274
+ except FileNotFoundError :
275
+ # just skip it if the secret file doesn't exist
276
+ pass
0 commit comments