Bitbucket - Webhook keep returning error 500 - laravel

Would like to check, I am fairly new to Bitbucket's new introduced webhook where previously i was using services where Bitbucket will execute a link to my site thus triggering a deployment script.
So since the old service is going to be depreciated soon, we all migrated to webhook instead. With the same implementation, I keep getting an error 500 upon commit/push/merge and there is no way for us to see the details for the error given. At first I thought it was my server giving problem but when i call the link manually via browsers and everything was fine. The deployment script can be executed successfully so then why bitbucket's webhook keeps telling me error 500?
Subsequently I find the guide given by Bitbucket was not helpful. There is no specified call method to the url stated so is the webhook initiates a GET or POST request? previously using services initiates a POST request. Then, are there any necessary payloads i need to include into the webhook URL? None is stated. Then, if there is an error at least let me see the error so I can fix it instead of telling me error 500.
I hope someone here can help me with this issue. Below are some specification of the site.
Server : Ubuntu LEMP 14.04 x64 Laravel framework 5.0
Webhook Url: bot.example.com/bitbucket/deploy/{Site API}
Method : GET
And when the abode link is call, it reaches a controller that does
public function attemptDeploy($site_api)
{
$script = 'nohup setsid php ~/scripts/deploy.php ' . $site_api. ' > /dev/null 2>&1 &';
exec($script);
return response('Deploy running.', 200);
}
Note that when i call this link manually either form browser or console everything works perfectly except from bitbucket's webhook. How can i solve this issue?

I was in the same situation. Bitbucket trims the body of the response and I couldn't see the error given by my server.
I've looked into the logs storage/logs/laravel.log and saw TokenMismatchException. Webhooks being API calls they don't store cookies or sessions so CSRF from Laravel breaks.
You need to add an exception from CSRF for the bitbucket deploy route. You can add this exception in app/Http/Middleware/VerifyCsrfToken.php. For example if your link is www.your_site.com/bit_deploy you will have:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'bit_deploy'
];
}
Hope that this helps you ... as I've lost 3 hours on this.
PS: at the time of writing this answer, bitbucket webhooks performs POST calls (not GET)

Related

laravel swift-mailer exception "Expected response code 250 but got an empty response" using gmail smtp-relay (database queue driver)

the gmail smtp-relay works fine using the sync driver, but if we queue the email we this error. cleared config, cache, & restarted queue workers. tested in prod and dev, same results
[2021-01-24 20:04:22] production.ERROR: Expected response code 250 but got an empty response {"exception":"[object] (Swift_TransportException(code: 0): Expected response code 250 but got an empty response at /home/****/****/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Transport/AbstractSmtpTransport.php:448)
were wondering is this because of serialization and something is not making it through that process???
using latest stable release of laravel >8.0. gmail smtp is authenticating just fine, per why the sync driver sends emails easily. maybe there needs to be a timeout on the queue jobs so they dont barrage gmail so quickly? also our code works fine using sendgrid for example as the smtp relay. thanks.
See https://laracasts.com/discuss/channels/laravel/laravel-swift-mailer-exception-expected-response-code-250-but-got-an-empty-response-using-gmail-smtp-relay-database-queue-driver
Update your AppServiceProvider.php
add this inside boot();
// Fix for SwiftMailer Service;
$_SERVER["SERVER_NAME"] = "your.domain.name";
For users of smtp-relay.gmail.com, if you use localhost/127.0.0.1 as domain during developments, you probably need to change the domain name to use in EHLO command to begin the transaction. I solved this by adding &local_domain=dev.mydomain.tld at the and of my DSN.
smtp://smtp-relay.gmail.com:587?encryption=tls&local_domain=dev.mydomain.tld&...
For SwiftMailer Symfony bundle (since 2.4.0), you can set the local_domain config parameter:
// config/packages/dev/swiftmailer.yaml
swiftmailer:
...
local_domain: dev.mydomain.tld
Explanation for the 2 previous Answers
if $_SERVER["SERVER_NAME"] is the solution:
When you are using cron
The reason is that $_SERVER["SERVER_NAME"] is null when cron is executed. $_SERVER["SERVER_NAME"] is usually only defined for http access.
Example implementation (laravel):
if (!isset($_SERVER['SERVER_NAME'])) {
$url = config('env.APP_URL');
$domain = mb_ereg_replace("http(s)? ://", "", $url);
$domainParts = explode('/', $domain);
ini_set('server_name', count($domainParts) > 0 ? $domainParts[0] : $domain)
}
References :
Cron Job $_SERVER issue
https://github.com/swiftmailer/swiftmailer/issues/992
if 'local_domain' is the solution
When you have a mailhost setting of MAIL_HOST=smtp-relay.gmail.com in your laravel project
The reason is that if local_domain' is not set, the protocol for mail communication with Gmail will be EHLO [127.0.0.1]` and the communication will be disconnected.
By the way, I used gmail->gmail alias and did not need relay in the first place, so I solved the problem by setting MAIL_HOST=smtp.gmail.com.
References:
https://blog.trippyboy.com/2021/laravel/laravel-expected-response-code-250-but-got-an-empty-response/
I had to deal with both of them because of cron messaging and MAIL_HOST=smtp-relay.gmail.com in my environment.
I hope this information will help you.

slash command "dispatch_failed"

I have went through creating the custom slash command configuration via slack and installed it on workspace. However when I run it I get this
/testing failed with the error "dispatch_failed"
I tried multiple workspaces but same issue. Anyone experienced this?
So after a few tests, I found out that this is just a generic message of anything that fails at slack at this point. I have first my endpoint that was unreachable. So it was returning this message. I fixed that, used ngrok for tunnel so that I could debug and that is how I found this issue.
Also, this error can occur due to the following reasons as well.
Errors in code
Unreachable backend or Invalidly configured slash command in the app
While the documentation tells you:
"use the Request URL is your base server link + "/slashcommand" after it"
This is incorrect. The request URL should be: "/slack/events"
Of course the command needs to match whats in the 'edit command' window and in the method '.command' in your app.js:
app.command('/flash-card', async ({ ack, body, client })
If you're using ngrok http <port> to test in your localhost, be aware that a new ngrok public URL is created every time you run this command. So in https://api.slack.com/apps, in your app's Features, you may have to update your Slash Command' request URL with the current ngrok URL generated for you.
You need to set the Method in the Integration Settings to GET, is default to POST
This is also the error for a 404 Not Found.
If you're developing offline with ngrok, the 404 error can be seen in the terminal.
If you're deploying with serverless, ensure that you're handling the new endpoint /slack/command. One solution is to create a separate handler, i.e. /command.js
functions:
slack:
handler: app.handler
events:
- http:
path: slack/events
method: post
command:
handler: command.handler
events:
- http:
path: slack/command
method: post
[If your code is executing and u still have this error]
In my case using Slackbolt with js I forgot to add
await ack();
in called function so Slack api throw error.

Bitcoind walletnotify configure on Laravel does not work

I have successfully configured bitcoind and connected it from a Laravel application. My issue now is walletnotify does not get triggered when a new transaction comes on an internally generated address.
bitcoin.conf
maxconnections=12
rpcuser=user
rpcpassword=pass
test.rpcport=18332
rpcallowip=0.0.0.0/0 --testing purposes
keypool=10000
server=1
testnet=1
txindex=1
walletnotify=/usr/bin/curl http://127.0.0.1/notify/%s
I have also tried with:
walletnotify=curl http://127.0.0.1/notify/%s
The route:
Route::get('/notify', 'HomeController#notify');
The Controller:
public function notify($tx) {
$txinfo = Bitcoind::getRawTransaction($tx, true);
$txinfo = $txinfo->get();
.....
}
Notes:
Blockchain is synced.
I have checked the debug.log from bitcoin but no errors from walletnotify or at least the curl when it should run.
If I manually call the route and pass a txid, everything goes well.
Thanks in advance for any help!
Problem solved!
WalletNotify config below works just fine.
walletnotify=curl http://127.0.0.1/notify/%s
The problem was I build the function that verifies the transaction in the HomeController, which is guarded by the AUTH middleware. As I started this for testing purposes, I forget about the guard from the HomeController which is created by laravel authentication scaffolding.

Trying to set up CAS with my Laravel project

I am using subfission/cas for my application. I have followed all installation steps. I am using windows, if that matters. More precisely, I have configured the following:
I ran the following in my terminal
composer require "subfission/cas" "dev-master"
I configured my Kernel.php accordingly, adding the following:
'cas.auth' => 'Subfission\Cas\Middleware\CASAuth',
'cas.guest' => 'Subfission\Cas\Middleware\RedirectCASAuthenticated',
I ran the following command:
php artisan vendor:publish
I also set up my cas server in my cas.php config file:
'cas_hostname' => env('CAS_HOSTNAME', 'cas.myserver.me'),
'cas_real_hosts' => env('CAS_REAL_HOSTS', 'cas.myserver.me'),
What I want is a middleware for all my routes, so I added the following route rule in my routes:
Route::middleware(['cas.auth'])->group(function ()
{
Route::get('/', function ()
{
return view('welcome');
});
});
Basically, I want to redirect everyone who is not logged in to the login page whenever I access the main page (for now, I will add more routes in the future). What happens is that the users are redirected to the login page when they are not logged in, but after the login I receive the following error:
ErrorException (E_WARNING)
DOMDocument::loadXML(): Opening and ending tag mismatch: hr line 1 and body in Entity, line: 1
No matter what view I'm redirecting the user to. I tried the default welcome page as well as an empty view, but I still get the same error.
EDIT: I have used the dev-master branch from subfission/cas for the above error and after switching to 2.1.1, I get a different error:
session_name(): Cannot change session name when headers already sent
EDIT 2: I did some more digging and I enabled internal errors in my cas client class with:
libxml_use_internal_errors(true);
And now I get the following:
Authentication failure: SA not validated Reason: bad response from the CAS server
And the cas response is:
The thing is that I use the same cas server for another 2 projects and it works well for those (but those aren't laravel projects.
I know it's been a while, but for anyone else having issues like this, the issue is the protocol selected for which your web service communicates with your CAS(Central Authentication Service) provider. There are two main protocols used for SSO/CAS in this package:
SAML(Security Assertion Markup Language) version 1.1 & 2
CAS Protocol v3.0
[Confusingly enough, CAS protocol shares the same namespace as the service.]
The idea is to match the protocol and version with your identity provider. It sounds like your provider is using CASv3.0, which is why disabling SAML worked.
Also, if you enable debug mode, you will see further error details in your log file to help your troubleshoot.
Best of luck!
I managed to solve the issue by disabling the SAML in the cas configure file:
'cas_enable_saml' => env('CAS_ENABLE_SAML', true),
change to
'cas_enable_saml' => env('CAS_ENABLE_SAML', false),

Laravel Socialite InvalidStateException in AbstractProvider.php line 200

I'm building a web app in my local system (Ubuntu-14.04 64Bit) using laravel 5.3. I used Socialite to signin from social networks. I configured G+, Facebook, GitHug. I'm using Chromium as my default browser. Finally the problem is i'm getting
InvalidStateException in AbstractProvider.php line 200
frequently. i tried
php artisan cache:clear
php artisan config:clear
composer dump-autoload
these are helping to solve the issue temporarily, again the problem raising.
please help me in this issue..
I have the same issue and I've read a lot about this, that depend if the URL where you are at the moment of the login request has www. at the beginning or not.
Into config\services.php, if you have the redirect set as http://sitename.tld/callback/facebook the oauth works if you send the login request from sitename.tld, while if you try from www.sitename.tld you get the exception.
I haven't yet understood how to have it working with and without www at the beginning.
If the AbstractProvider.php line 200 fires the exception when the state of the user is not present means that the User cannot be created.
First check your code when you get the details from the provider(facebook, github) if you create a user and you return it.
If you have managed and logged in your app and you deleted the user from the user table remember to delete also the data from the socialite account table.
I was getting that exception because 'state' wasn't saved in session. But I was using asPopup method - Socialite::driver('facebook')->asPopup()->redirect(); so I saved session then - $request->session()->save();. So I solved this issue.
or try
session()->put('state', $request->input('state'));
$user = Socialite::driver('facebook')->user();
it works
I have same issue and solved in 3 steps;
add request on the top
use Illuminate\Http\Request;
Pass request object to function
public function handleProviderCallback(Request $request)
{
try {
$user = Socialite::driver('facebook')->user();
} catch (Exception $e) {
throw new Exception;
}
}
Clear cache.
php artisan cache:clear
I had the same error but my solution was a little different. I am posting here just in case someone else keeps hitting this post like I did for a possible answer.
I develop on Ubuntu 18.04 desktop since it is a server with a GUI. Socialite works great locally but as soon as I pushed/pulled the changes through git to the server, it quit.
I was running traces by recording what was sent to and from google. I "dd($_GET)" to get a raw dump before Socialite had a chance to get the info so I knew what was stored and ready for use. All info was there but Socialite didn't seem to "see" it. That is when I reasoned it was my apache2 header configuration interfering with the cookies/session data.
I had set header security in my apache2 configs. One of the settings was
Header always edit Set-Cookie ^(.*) "$1;HttpOnly;Secure;SameSite=Strict"
This setting was interfering with the cookie information that socialite needed. I removed that setting from my apache2 header config(by commenting out) and restarted Apache. Finally I removed all sessions in storage/framework/session/* and cleared them from my browser just to be sure. That worked for me.
After I got it working, one by one enabled and tested each of the following settings to have the framework secure what header info it can:
SESSION_SECURE_COOKIE=true
in my .env file
'http_only' => true, and
'same_site' => 'lax'(setting to "strict" did not seem to work)
in my config/session.php file.
Now it is back to testing security and tweaking things back if need be.

Resources